交错的CSS动画

我有一个CSS动画,我希望以200ms的间隔应用。 我已经设置了这样的CSS:

.discrete { position:relative; opacity:1; -webkit-transition: all .5s linear; -moz-transition: all .5s linear; -o-transition: all .5s linear; transition: all .5s linear; } .discrete.out { left:-40px; opacity:0; } 

然后我想以200ms的间隔错开.discrete.out类的应用程序。 我尝试过以下方法:

 $('.discrete').each(function() { $(this).delay(200).addClass('out'); }); 

还有这个:

 $('.discrete').each(function() { var theNode = $(this); setTimeout(function() { theNode.addClass('out'); }, 200); }); 

但在这两种情况下,动画都会立即发生!

有任何想法吗?

你可以用

 var els = $('.discrete'), i = 0, f = function () { $(els[i++]).addClass('out'); if(i < els.length) setTimeout(f, 200); }; f(); 

演示

尝试使用jQuery动画队列: http : //jsfiddle.net/gwwar/7zm6q/2/

 function createWorkQueueFunction($element) { return function(next) { $element.addClass("out"); next(); }; } $('button').click(function() { var queue = $({}); //use the default animation queue $(".discrete").each(function() { queue.queue(createWorkQueueFunction($(this))); queue.delay(200); }); }); 

但为什么你的例子不起作用?

以下不起作用的原因是因为jQuery会在向fx队列添加200 ms延迟后立即添加’out’类。 换句话说,delay()不会暂停未添加到队列的项目。 请参阅: jQuery中的队列是什么? 有关jQuery队列如何工作的更多信息。

$(’。discrete’)。each(function(){$(this).delay(200).addClass(’out’);});

在第二个示例中,您将为每个.discrete元素添加相同的超时。 因此,在大约200ms后,每个人几乎同时会添加一个类。 相反,您可能希望为每个元素设置200ms的超时,然后是400ms,然后是600ms等等。

$(’。discrete’)。each(function(){var theNode = $(this);
setTimeout(function(){theNode.addClass(’out’);},200); });