我在jquery中停止循环if语句时遇到问题。我的想法是我有一个div,它应该开始循环彩虹数组中的所有颜色,并在点击停止div时停止。它循环很好,但是当我点击停止时,即使循环变量为0,它也不会停止循环。当我点击停止时,我该怎么办才能让颜色停止?
点击here获取指向我编码的jsfiddle页面的链接。
$(document).ready(function () {
//Defines variables.
var loop = 1;
var rainbow = ["red", "orange", "yellow", "green", "blue", "purple"];
//loops the color changing if 'loop' is 1.
$('#go').click(function strobe() {
if (loop) {
for (var i = 0; i < rainbow.length; i++) {
$('#color').animate({
"background-color": rainbow[i]
}, 500);
}
strobe();
}
});
//Sets 'loop' to 0 to prevent looping.
$('#stop').click(function () {
loop = 0;
});
});
答案 0 :(得分:3)
您需要清除队列,所以
$(document).ready(function () {
//Defines variables.
var loop = true,
//current color index
current = 0;
var rainbow = ["red", "orange", "yellow", "green", "blue", "purple"];
function strobe() {
if (loop) {
if (current >= rainbow.length) {
//reset to initial color
current = 0;
}
$('#color').animate({
"background-color": rainbow[current++]
}, 500, strobe);
}
};
//loops the color changing if 'loop' is 1.
$('#go').click(function () {
//restart the animation
loop = true;
strobe();
});
//Sets 'loop' to 0 to prevent looping.
$('#stop').click(function () {
loop = false;
$('#color').stop(true)
});
});
演示:Fiddle
答案 1 :(得分:3)
现在,在调用下一次迭代之前,您不会等待动画结束。如果您查看控制台,您应该会看到堆栈溢出错误,因为您的函数会立即调用它自己。
这是一个解决方案:
//Defines variables.
var loop = 1, i=0;
var rainbow = ["red","orange","yellow","green","blue","purple"];
//loops the color changing if 'loop' is 1.
$('#go').click(function strobe(){
if(loop){
$('#color').animate({"background-color":rainbow[i]}, 500, strobe);
i = (i+1)%rainbow.length;
}
});
//Sets 'loop' to 0 to prevent looping.
$('#stop').click(function(){
loop = 0;
});
答案 2 :(得分:2)
$(function(){
var $color = $('#color'); // Cache your elements!!
var rainbow = ["red","orange","yellow","green","blue","purple"];
var i = 0;
var n = rainbow.length;
function loop(){
$color.stop().animate({backgroundColor:rainbow[++i%n]}, 500, loop);
}
function stop(){
$color.stop();
}
$( '#go' ).click(loop);
$('#stop').click(stop);
});
直截了当,通过回忆loop
回调 animate()
, 500, loop);
来简单地实现循环
答案 3 :(得分:0)
你的for语句正在进行循环,你需要另一个条件来打破它。尝试将i<rainbow.length
替换为((i < rainbow.length) && (loop != 0))
答案 4 :(得分:0)
另一种方法是使用setInterval
:
var rainbow = ["red","orange","yellow","green","blue","purple"];
var interval,i = 0;
$('#go').click(function(){
interval = setInterval(function() {
i = (i+1)%rainbow.length;
$('#color').animate({"background-color":rainbow[i]},500);
},500);
});
$('#stop').click(function(){
clearInterval(interval);
});