如何在不堆叠回调的情况下在 jQuery 中设置动画? [英] How do I animate in jQuery without stacking callbacks?

查看:36
本文介绍了如何在不堆叠回调的情况下在 jQuery 中设置动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个 div,我希望每个 div 都在前一个完成后进行动画处理.目前,我写这个:

Let's say I have three divs, and I'd like each to animate once the previous one is done. Currently, I write this:

$('div1').fadeOut('slow', function() {
    $('div2').fadeOut('slow', function() {
        $('div3').fadeOut('slow');
    });
});

这很丑陋,但可以管理.

Which is ugly, but manageable.

现在假设我有 10 个不同的动画,它们需要一个接一个地在不同的元素上发生.突然间,代码变得如此笨拙,以至于管理起来非常困难......

Now imagine I have 10 different animations that need to happen one after the other on different elements. Suddenly the code gets so clunky that it's extremely hard to manage...

这是我要执行的操作的伪代码:

Here's pseudocode for what I'm looking to do:

$('div1').fadeOut('slow' { delay_next_function_until_done: true } );
$('div2').fadeOut('slow' { delay_next_function_until_done: true } );
$('div3').animate({ top: 500 }, 1000 );

我如何实现这一目标?

推荐答案

如果您使用的是最新版本的 jQuery,请使用动画承诺:

If you're using a recent version of jQuery, use the animation promises:

$('div1').fadeOut('slow').promise().pipe(function() {
    return $('div2').fadeOut('slow');
}).pipe(function() {
    return $('div3').animate({ top: 500 }, 1000 );
});

您可以将其设为通用:

$.chain = function() {
    var promise = $.Deferred().resolve().promise();
    jQuery.each( arguments, function() {
        promise = promise.pipe( this );
    });
    return promise;
};

var animations = $.chain(function() {
    return $('div1').fadeOut('slow');
}, function() {
    return $('div2').fadeOut('slow');
}, function() {
    return $('div3').animate({ top: 500 }, 1000 );
});

$.when( animations ).done(function() {
    // ALL ANIMATIONS HAVE BEEN DONE IN SEQUENCE
});

仍然有很多函数闭包,但这就是 Javascript 的本质.但是,使用 Deferreds/Promises 会更自然,更灵活,因为您可以避免回调inception".

Still a lot of function closures but that's the very nature of Javascript. However, it's much more natural and a lot more flexible using Deferreds/Promises since you avoid callbacks "inception".

这篇关于如何在不堆叠回调的情况下在 jQuery 中设置动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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