我正在尝试使用<delay>
来延迟事件,例如更改背景颜色。我希望事件遵循我想要的延迟时间,但结果表明它们不符合我想要的顺序。我期待第一个在1秒内变红。然后第二个在2秒内变红。然后第三个在0.8秒内变红。我不知道如何让它们变成不同的颜色。非常感谢你的帮助。
$(document).ready(function(){
var delayTime = [1000, 2000, 800];
var bcolor = ['red','blue','green'];
var i = 0;
$('#play').click(function(){
$('div').each(function(){
$(this).delay(delayTime[i]).queue( function(next){
$(this).css('background','red');
next();
});
i++;
}); // end of each
});
}); // end ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="red" style="width:100px; height: 100px; background-color: white" ></div>
<div id="blue" style="width:100px; height: 100px; background-color: white"></div>
<div id="green" style="width:100px; height: 100px; background-color: white"></div>
<button id="play">Play</button>
<h1 id="test"></h1>
您还需要使用循环来拾取颜色:
$(document).ready(function() {
var delayTime = [1000, 2000, 800];
var bcolor = ['red', 'blue', 'green'];
var i = 0;
$('#play').click(function() {
$('div').each(function() {
var bg = bcolor[i]; // here update value color
$(this).delay(delayTime[i]).queue(function(next) {
$(this).css('background', bg);
next();
});
i++;
}); // end of each
});
}); // end ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="red" style="width:100px; height: 30px; background-color: white"></div>
<div id="blue" style="width:100px; height: 30px; background-color: white"></div>
<div id="green" style="width:100px; height: 30px; background-color: white"></div>
<button id="play">Play</button>
<h1 id="test"></h1>
1st:您可以使用index of div
而不是i=0;
2nd:对于延迟时间,您可以将以前的时间添加到新的时间中以获得正确的延迟时间。。因此,如果你有[10002000],新的延迟时间将是1000,然后是3000,然后是3800,依此类推
你可以使用这个代码
$(document).ready(function(){
var delayTime = [1000, 2000, 800];
var bcolor = ['red','blue','green'];
var timeDelay = 0;
$('#play').click(function(){
$('div').each(function(i){ // i mean index of div starts from 0
timeDelay += delayTime[i]; // add a pervious delayTime (the trick here)
$(this).delay(timeDelay).queue( function(){
$(this).css('background', bcolor[i]); //use bcolor[i] to get a color
});
}); // end of each
});
}); // end ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="red" style="width:100px; height: 100px; background-color: white" ></div>
<div id="blue" style="width:100px; height: 100px; background-color: white"></div>
<div id="green" style="width:100px; height: 100px; background-color: white"></div>
<button id="play">Play</button>
<h1 id="test"></h1>
我不太喜欢jQuery,但我可以看到你在下面的行上有固定的颜色值:
$(this).css('background','red');
也许这就是问题的根源?