Adding a sequence of animations to a single dom element using jQuery is extremely easy. jQuery queues everything up nicely for me and I basically don't have to do anything.
However making a sequence of animations over a number of elements (eg pictureDiv fades out, then demographicsDiv fades in) is much harder. I've written a plugin type thing to make it easier as below:
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)
})
}
}
}
Which is used thusly
var animationQueue = something.createAnimationQueue();
animationQueue.add(pictureDiv, pictureDiv.fadeOut, 'slow');
animationQueue.add(demographicsDiv, demographicsDiv.fadeIn, 'slow');
My questions are:
1) Have I missed something? Is there an easier way of doing this that I didn't know about.
2) If not, is there a way to avoid passing pictureDiv and pictureDiv.fadeOut to the animationQueuer? (I tried and couldn't think of one)
Thanks!
Since you are using .apply and reassigning this, you could simply use
var animationQueue = something.createAnimationQueue();
animationQueue.add(pictureDiv, $.fn.fadeOut, 'slow');
animationQueue.add(demographicsDiv, $.fn.fadeIn, 'slow');
And if you really wanted to, you could turn that into a string:
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'); // <----
Note, however, this can't be used for more than just animations now. You could use this with any jQuery method that returns a promise object, such as .ajax, .post, .get, .getJSON, etc. if you used it like you originally had it.
来源:https://stackoverflow.com/questions/12675275/writing-a-global-animation-queue-in-jquery