如何让动画一一运行? [英] How can I make the animations be run one by one?

查看:16
本文介绍了如何让动画一一运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

抱歉迟到了.

当计时器阻塞并依赖计时器的准确性时,现有答案存在问题,而且它们需要实际延迟.

The existing answers have issues when a timer blocks and rely on the accuracy of timers, moreover they require an actual delay.

jQuery 实际上提供了一种通用的方式来使用 promise 顺序执行动画:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆