【问题标题】:Sequential animations not working with jQuery promises顺序动画不适用于 jQuery 承诺
【发布时间】:2015-04-18 01:07:25
【问题描述】:

我正在尝试运行 3 个动画,一个接一个,这样只有在第一个动画完成后,第二个动画才开始,只有在第二个动画完成后,第三个动画才开始。

我可以使用嵌套的 jQuery 动画回调来做到这一点

    go("one", function () {
        go("two", function () {
            go("three", null);
        });
    });

http://jsfiddle.net/stevenc/m0en7avd/2/

但是,我希望能够使用 jQuery 承诺/延迟来做到这一点。我一直在创建一个延迟对象并返回它的承诺。动画回调现在将 promise 设置为已解决,并且只有在这一点上我才期望“then”开始:

go("one").then(go("two")).then(go("three"));

但会发生的是所有动画同时开始。

http://jsfiddle.net/stevenc/wsqm6yo1/11/

谁能看到我错过了什么?

【问题讨论】:

    标签: jquery animation promise deferred


    【解决方案1】:

    您是在调用函数而不是调用它们,您的代码如下所示,带有回调:

    go("one", go("two", go("three")))
    

    相反,链接函数:

    go("one").then(function(){ return go("two"); }).
              then(function(){ return go("three"); });
    

    你可以see in this fiddle

    或者使用bind,它返回一个带有固定参数的函数:

    go("one").then(go.bind($, "two")).then(go.bind($, "three"));
    

    你可以see here。请注意,您的代码中还有 the deferred anti pattern - 您的 go 函数可以简化为:

    function go(id, c) {
        return $("#" + id).animate({
            left: "300px"
        }).promise()
    }
    

    【讨论】:

    • 谢谢本杰明,很好的回复!
    猜你喜欢
    • 2017-03-20
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2019-11-01
    • 2018-01-06
    • 2019-06-16
    • 2021-09-08
    • 2012-09-22
    相关资源
    最近更新 更多