繁体   English   中英

延迟事件,例如更改 div 的背景颜色

[英]delay on an event, such as change background color of div

我正在尝试使用<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>

第一:代替i=0; 您可以使用index of div

第二:对于延迟时间,您可以将以前的时间添加到新的时间以获得正确的延迟时间..所以如果您有 [1000 , 2000 , 800] 新的延迟时间将是 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');

也许这导致了问题?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM