[英]How to get timing & sequence right in jQuery
Assume we have three light bulbs, and I want to glow the first one, keep it on for a few milliseconds, turn it off, turn on the next and continue in the same way. 假设我们有三个灯泡,我想让第一个灯泡发光,将其点亮几毫秒,将其关闭,打开下一个灯泡,然后以相同的方式继续。
Turning the light bulbs on and off is done by adding and removing a class. 通过添加和删除类来打开和关闭灯泡。 How do I achieve this?
我该如何实现?
PS I used light bulbs just to make my question clearer. PS我用灯泡只是为了使我的问题更清楚。 Basically what I need is, how to add a class to a div, keep it for some time, remove class, apply a class to another div, keep it for some time and remove it and so on...
基本上我需要的是如何将一个类添加到div中,保留一段时间,删除类,将一个类应用于另一个div,保留一段时间并删除等等...
*Edit Clarification: The number of bulbs is dynamic *编辑说明:灯泡数量是动态的
您可以使用setInterval和jquery selecors的简单组合。检查此提琴http://jsfiddle.net/aqXtL/1/
The Javascript function setInterval(code, interval) will repeatedly execute code with your interval. Javascript函数setInterval(code,interval)将按照您的时间间隔重复执行代码。 Just keep a variable with a counter, and use jquery's addClass and removeClass to turn the lights on and off.
只需保留一个带有计数器的变量,然后使用jquery的addClass和removeClass来打开和关闭灯。
you can use setTimeout like setTimeout(yourfuncname, 3000) == wait 3 seconds then run that function. 您可以像setTimeout(yourfuncname,3000)这样使用setTimeout ==等待3秒钟,然后运行该函数。 If you need to use animations then the jquery
animate
method has a completed callback as a parameter. 如果您需要使用动画,则jQuery
animate
方法将完整的回调作为参数。
very simplified example... 非常简化的示例...
function startDimming(){
setTimeout(_interval,function(){
// Remove all "glowing" bulbs.
// Add class to first "bulb".
setTimeout(_interval,function(){
// Remove all "glowing" bulbs.
// Add class to second "bulb".
setTimeout(_interval,function(){
// Remove all "glowing" bulbs.
// Add class to last "bulb".
startDimming();
});
});
});
}
You can use the animation of jquery and use the complete function to do other tasks. 您可以使用jquery的动画并使用complete函数来完成其他任务。
.animate( properties [, duration] [, easing] [, complete] ) $('#clickme').click(function() { $('#book').animate({ opacity: 0.25, left: '+=50', height: 'toggle' }, 5000, function() { // Here you have animated the object and the animation is complete, so // you can start a new animation here }); });
HTML : HTML:
<div class="bulb"> </div>
<div class="bulb"> </div>
<div class="bulb"> </div>
CSS: CSS:
.bulb {
width: 50px;
height: 100px;
border: 2px #000 solid;
float: left;
margin: 10px;
}
.bulb.on {
background: #ff0;
}
Jquery : jQuery的:
var timer;
function light ( i ) {
i = i % $(".bulb").length;
$(".bulb").eq(i).addClass("on").siblings().removeClass("on");
timer = setTimeout(function(){
light( ++i );
}, 1000);
}
$(document).ready( function() {
light(0);
});
Edit : here's a working sample, http://jsfiddle.net/QdWgM/ 编辑:这是一个工作示例, http://jsfiddle.net/QdWgM/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.