如何使动画一一播放? [英] How can I make the animations be run one by one?
问题描述
HTML代码:
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
<li>e</li>
</ul>
js代码:
<script type="text/javascript">
$(document).ready(function() {
var lis = $("li");
for (var i = 0; i < lis.length; i++) {
$(lis[i]).animate({opacity: 0}, 1000);
}
});
</script>
我只是发现lis会一起消失.我该怎么办,它们会一一消失?
I just find that the lis will disappear together. How can I do that they will disappear one by one?
推荐答案
对不起,您参加晚了.
Sorry for joining the party late.
当计时器阻塞并依赖计时器的准确性时,现有的答案会出现问题,而且它们需要实际的延迟.
The existing answers have issues when a timer blocks and rely on the accuracy of timers, moreover they require an actual delay.
jQuery实际上提供了一种通用的方式来按顺序执行带有诺言的动画:
jQuery actually provides a generic way to perform animations sequentially with promises:
$(document).ready(function() {
var lis = $("li");
var queue = $.Deferred().resolve(); // create an empty queue
lis.get().forEach(function(li){
queue = queue.then(function(){
return $(li).animate({opacity: 0}, 1000).promise();
})
});
});
请注意,即使您为它们分配了不同的动画持续时间或不同的动画,这也将起作用,queue
中的结果将在最后一个动画结束时包含一个钩子.这也支持聚合(等待所有诺言并行完成)和更多.
Note that this will work even if you assign them different animation durations or different animations, the result in queue
will contain a hook on when the last animation finished. This also supports aggregations (waiting for all promises to finish in parallel) and more.
这篇关于如何使动画一一播放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!