我有以下代码:
<div class="drawing1"></div>
<button id="start">Begin</button>
当用户点击Button时,分配给DIV元素的类应该从drawing1更改为drawing5,并在其间穿过每个绘图(总共有5个绘图)。它也应该有大约500的延迟()。我的第一个想法是:
$('div').delay(800).toggleClass('drawing1 drawing2');
哪个有效,但是当我尝试添加其余的图纸时(使用toggleclass和添加/删除类尝试了几个方法),它会跳转到最后一个或只执行第二个。
如何进行设置,以便我可以从一个绘图类进入下一个绘图类,逐个遍历每一个绘图类,并逐个应用延迟。
答案 0 :(得分:3)
var i = 2; //Assumes drawing1 is already applied to the div
var nextDrawing = function(){
$("div").removeClass()
.addClass("drawing"+i);
i = ((i + 1) % 5); //To cycle from 1 to 5
i = i == 0 ? 5 : i;
}
$('#start').click(function(){
setInterval(nextDrawing, 500);
});
应该做的伎俩。
编辑:如果有人多次点击该按钮,以下修改可能对某人有用以清除间隔。
var i = 2; //Assumes drawing1 is already applied to the div
var nextDrawing = function(){
$("div").removeClass()
.addClass("drawing"+i);
i = ((i + 1) % 5); //To cycle from 1 to 5
i = i == 0 ? 5 : i;
}
var intervalID = undefined;
$('#start').click(function(){
if( intervalID != undefined )
{
clearInterval(intervalID);
}
intervalID = setInterval(nextDrawing, 500);
});
以下是一个工作示例:http://jsfiddle.net/ajhuU/
答案 1 :(得分:0)
var leMethod = function(){ // wrapping in a method localizes variables
var max = 5; // nr of drawings
var activeIdx = 0; // active drawing
var timeout = 500; // the time between changes
var originalClass = 'some classes that are always there';
setTimeout(function(){ // execute the method on timeout expiration
var el = $('div'); // get whatever element you wish to manage
el.attr('class', originalClass); // restore original class
el.addClass('classNr'+activeIdx); // add your cycle class
activeIdx = (activeIdx+1) % max; // update index
}, timeout);
};
leMethod();