gpt4 book ai didi

jQuery:通过数组无限循环...each()?

转载 作者:行者123 更新时间:2023-11-30 23:49:37 24 4
gpt4 key购买 nike

在这里摆弄: http://jsfiddle.net/F6nJu/

我有一个彩色盒子:

<div id="colorblock"></div>
#colorblock { background:#3ff; width: 100%; height: 300px; }

我在 javascript 中创建了一个颜色数组:

var arr = [ "#f00", "#ff0", "#f0f", "#f66"];

我使用 jQuery each() 函数迭代这些颜色:

$.each(arr, function(key, value) {
$('#colorblock').delay('1200').animate({backgroundColor:value}, 600);
});

当数组迭代到最后时,如何重新开始数组迭代(以便动画永远持续下去)?

最佳答案

var arr = ["#f00", "#ff0", "#f0f", "#f66"];

// run through the array forever
(function recurse(counter) {
// get the colour
var color = arr[counter];
// animate it
$('#colorblock').delay('1200').animate({
backgroundColor: color
}, 600);
// delete the value to save memory
delete arr[counter];
// add the value at the end of the array
arr.push(color);
// run it again for the next number
setTimeout(function() {
recurse(counter + 1);
}, 200);
// start it for the first number.
})(0);

无限递归。删除当前条目,然后将当前值添加到末尾。

Live Example

对于那些对数组的外观感兴趣的人:

["#foo", "#ff0", "#f0f", "#f66"] (counter = 0)
[undefined, "#ff0", "#f0f", "#f66", "#foo"] (counter = 1)
[undefined, undefined, "#f0f", "#f66", "#foo", "#ff0"] (counter = 2)
[undefined, undefined, undefined, "#f66", "#foo", "#ff0", "#f0f"] (counter = 3)
[undefined, undefined, undefined, undefined, "#foo", "#ff0", "#f0f", "#f66"] (counter = 4)
etc.

关于jQuery:通过数组无限循环...each()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6051471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com