我有一些文字,我想在一段时间后改变。我有这个工作:
function nextMsg() {
if (messages.length == 0) {
} else {
$('#message').html(messages.pop()).fadeIn(500).delay(1000).fadeOut(500, nextMsg);
}
};
var messages = [
"sleep",
"eat",
"drink",
"read",
].reverse();
$('#message').hide();
nextMsg();
请参阅JSFIDDLE
我的问题: 我想继续重复这些消息。换句话说,当显示最后一条消息时,从第一条消息再次开始循环,创建一个无限循环。需要更改/添加到代码中的内容是什么?
答案 0 :(得分:4)
将counter
与%
var counter = 0;
function nextMsg() {
$('#message').html(messages[counter % messages.length]).fadeIn(500).delay(1000).fadeOut(500, nextMsg);
++counter;
};
var messages = [
"sleep",
"eat",
"drink",
"read",
];
$('#message').hide();
nextMsg();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p>
Things to do: <span id="message"></span>
</p>
&#13;
答案 1 :(得分:2)
类似this之类的东西。
<强> JS 强>
var i=0;
function nextMsg() {
$('#message').html(messages[i]).fadeIn(500).delay(1000).fadeOut(500, nextMsg);
i = (++i)%messages.length;
};
var messages = [
"sleep",
"eat",
"drink",
"read",
].reverse();
$('#message').hide();
nextMsg();
答案 2 :(得分:1)
我希望这对你有用。
var fadeLoop = function($el) {
$el.fadeOut(1000, function() {
var $next = $el.next();
if ($next.length == 0) {
$next = $el.siblings(":first");
}
$next.fadeIn(1000, function() {
fadeLoop($next);
});
});
};
$(document).ready(function(){
$("#elm1").siblings().hide();
fadeLoop($("#elm1"));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
Things to do:
<div >
<span id="elm1">sleep</span>
<span id="elm2">eat</span>
<span id="elm3">drink</span>
<span id="elm4">read</span>
</div>
&#13;