【问题标题】:How can I make my script wait for jQuery animate to finish?如何让我的脚本等待 jQuery 动画完成?
【发布时间】:2012-01-03 01:28:53
【问题描述】:

我有一个名为 runUpdates 的函数,我将一个 JSON 对象数组传递给它。此函数查看对象并具有 if 语句来确定它是哪种更新以及处理该更新应采取的方向。在某些情况下,更新具有与之相关的动画。我想使用 jQuery 的 animate 来为这些设置动画,但我希望它在继续下一步之前等待动画完成。

我的程序看起来像这样-

runUpdates(updates) {
    for(i = 0; i < updates.length; i++) {
        update = updates[i];
        if(update.type = "blabla") {
            //do stuff
        } else {
            //do other stuff
            if(update.animations) {
                for(k = 0; k < animations.length; k++) {
                    //do jquery animate AND wait for animation to finish before proceeding
                }
            }
        }
    }
}

但即使在动画开始后脚本也会继续运行。有没有一种简单的方法来解决这个问题,还是我需要用函数调用重新发明循环?

【问题讨论】:

  • 动画是否有动画结束事件?
  • 我怀疑您将不得不重组循环以使用函数调用。 jQuery 的 .animate() 有一个完整的回调,您可以使用它来启动流程的下一步。
  • 看起来像这样 - 为什么不向我们展示一些真实代码?!

标签: javascript jquery animation jquery-animate


【解决方案1】:

您的问题不是很清楚您要等待什么。我假设您要等待每个动画完成,然后再继续下一个。

var pipe = $.Deferred().resolve();

for(var k = 0; k < animations.length; k++)
{
    pipe = pipe.pipe(function()
    {
        return $('element').animate({
            // animate whatever you want
        }, 300);
    });
}

这是一个演示:http://jsfiddle.net/ZyS6c/


如果您想在所有动画完成后运行一些代码,请将其放入done 函数中:

pipe.done(function()
{
    // Put your code here...
});

...这是小提琴:http://jsfiddle.net/ZyS6c/1/


如果您对链接动画不感兴趣(您希望它们异步执行),并且只想在所有动画完成后运行一些代码,请使用:

var deferreds = [];

for(var k = 0; k < animations.length; k++)
{
    deferreds.push(
        $('element').animate({
            // animate whatever you want
        }, 300)
    );
}

$.when.apply($, deferreds).done(function()
{
    // Put your code here...
});

...最后,这是小提琴:http://jsfiddle.net/pdDME/

【讨论】:

  • 不是用pipe链接所有动画承诺,更自然的方法是用jQuery.when等待多个承诺。
  • @Ates Goral - 你能编辑我的小提琴并在此处发布链接吗?我不确定我是否在关注你。您将如何使用when 实现这一点?
【解决方案2】:

首先你可以使用jQuery的动画回调——http://jsfiddle.net/zutBh/1/

第二个是jQuery.deffereds对象。

【讨论】:

    猜你喜欢
    • 2014-01-21
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 2017-03-15
    • 2019-01-01
    • 1970-01-01
    相关资源
    最近更新 更多