在jquery中编写全局动画队列

使用jQuery将一系列动画添加到单个dom元素非常简单。 jQuery很好地为我排队,我基本上不需要做任何事情。

然而,在一些元素上制作一系列动画(例如pictureDiv淡出,然后demographicsDiv淡入)要困难得多。 我写了一个插件类型的东西,使其更容易,如下所示:

var something.createAnimationQueue = function () { // jQuery queues up animations on each dom element (/ jquery object) // We want to queue up animations over different dom elements so // use a jquery object on a blank element var animationQueue = $({}); return { add: function (animationFunctionContext, animationFunction) { var args = $.makeArray(arguments).slice(2); animationQueue.queue(function (next) { $.when(animationFunction.apply(animationFunctionContext, args)).done(next) }) } } } 

这就是使用的

  var animationQueue = something.createAnimationQueue(); animationQueue.add(pictureDiv, pictureDiv.fadeOut, 'slow'); animationQueue.add(demographicsDiv, demographicsDiv.fadeIn, 'slow'); 

我的问题是:

1)我错过了什么吗? 有没有更简单的方法来做这个我不知道的事情。

2)如果没有,有没有办法避免将pictureDiv和pictureDiv.fadeOut传递给animationQueuer? (我试过,想不到一个)

谢谢!

由于您正在使用.apply并重新分配,因此您可以使用

 var animationQueue = something.createAnimationQueue(); animationQueue.add(pictureDiv, $.fn.fadeOut, 'slow'); animationQueue.add(demographicsDiv, $.fn.fadeIn, 'slow'); 

如果你真的想,你可以把它变成一个字符串:

 var something.createAnimationQueue = function () { // jQuery queues up animations on each dom element (/ jquery object) // We want to queue up animations over different dom elements so // use a jquery object on a blank element var animationQueue = $({}); return { add: function (animationFunctionContext, method) { // <---- var args = $.makeArray(arguments).slice(2); animationQueue.queue(function (next) { $.when($.fn[method].apply(animationFunctionContext, args)).done(next) // <---- }) } } } var animationQueue = something.createAnimationQueue(); animationQueue.add(pictureDiv, 'fadeOut', 'slow'); // <---- animationQueue.add(demographicsDiv, 'fadeIn', 'slow'); // <---- 

但请注意,现在这不仅仅用于动画。 你可以在任何返回promise对象的jQuery方法中使用它,例如.ajax,.post,.get,.getJSON等,如果你像原来那样使用它。