如何在不堆叠回调的情况下在jQuery中进行动画制作? [英] How do I animate in jQuery without stacking callbacks?
问题描述
$ $ $'''code> $('div1')。fadeOut('slow',function(){
$('div2')。fadeOut('slow',function(){
$('div3')。fadeOut('slow');
});
});
这是丑陋的,但易于管理。
现在想象我有10个不同的动画需要在不同的元素之后发生。突然之间,代码变得非常笨重,以至于很难管理......
这是我正在寻找的伪代码:
$('div1')。fadeOut('slow'{delay_next_function_until_done:true});
$('div2')。fadeOut('slow'{delay_next_function_until_done:true});
$('div3')。animate({top:500},1000);
我如何实现这一目标?
如果您使用的是最新版本的jQuery,请使用动画承诺:
$('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);
});
返回承诺;
};
var animations = $ .chain(function(){
return $('div1')。fadeOut('slow');
},function(){
return $('div2')。fadeOut('slow');
},function(){
return $('div3')。animate({top:500},1000);
});
$ .when(动画).done(函数(){
//所有动画都已经按照顺序完成
});
还有很多函数闭包,但这就是Javascript的本质。但是,使用延迟/承诺会更自然,更灵活,因为您避免了初始回调。
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.
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 );
How do I achieve this?
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 );
});
You can make it generic:
$.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
});
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屋!