jQuery中同步的动画,不使用回调? [英] Synchronous animations in jQuery, not using callbacks?

查看:175
本文介绍了jQuery中同步的动画,不使用回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能使用,因为回调我有这样的(伪code)的方案:

I can't use callbacks because I have a scenario like this (pseudo-code):

$('.box').on('click', function() {
    $('.expanded-box').animate({
        // shrink it
    });

    $(this).animate({
        // grow it
        $(this).addClass('expanded-box');
    });
});

我不能把回调的扩展盒增长动画,因为它可能不会总是发生在扩展动画。但我需要的第二个动画要等到previous一个完成。我怎样才能做到这一点?

I can't put the expansion animation within the callback for the expanded-box growth animation because it may not always happen. But I need the second animation to wait till the previous one is done. How can I do this?

推荐答案

由于jQuery的1.6,可以使用承诺()以获得无极对象的当一个给定元素的所有动画已完成,将得到解决。此外,该文件说:

Since jQuery 1.6, you can use promise() to obtain a Promise object that will be resolved when all animations on a given element have completed. In addition, the documentation says:

这是一个集合使用.promise()没有活动的动画返回
  解决承诺。

Using .promise() on a collection with no active animation returns a resolved Promise.

因此​​,它非常适合于您的使用情况,你可以这样写:

Therefore, it's well-suited to your use case, and you can write:

$('.box').on('click', function() {
    var $this = $(this);
    $('.expanded-box').animate({
        // shrink it
    }).promise().done(function() {
        $this.animate({
            // grow it
        }).addClass('expanded-box');
    });
});

这篇关于jQuery中同步的动画,不使用回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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