动画前的回调函数

时间:2013-09-11 06:45:48

标签: jquery

实际上,在动画完成后调用回调函数

(selector).animate({styles},speed,easing,callback)

如何在动画开始前调用回调函数?

  

或者像这样,当动画同时运行时,如何调用回调函数?

2 个答案:

答案 0 :(得分:1)

如果callback是一个函数,只需在animate

之前调用它
callback();
(selector).animate({styles},speed,easing,callback)

答案 1 :(得分:0)

function animate(preCallback, postCallback) {

    // Create var to hold animating object if you want to use deffereds
    var animation;

    // Animation is about to start run preCallback()
    // If you don't want the animation to start until this is complete
    // You should look at returning a deffered object from the callback
    // or using another callback inside, warning : this can get messy.
    preCallback instanceof Function && preCallback();

    // Start the animation
    animation = $('#animation').animate({styles}, speed, easing, function() {
        // Once animation is finished run finished callback
        postCallback instanceof Function && postCallback();
    });

    // Alternative Return animation as deffered so further 
    // complete callbacks can be chained to it with .done()
    return $.when(animation);
}

animate(function() {
    // preCallback code, this will NOT stop animation from starting
    // before it is complete without further logic
}, function() { 
    // postCallback code
}).done(function() {
    // further callback using deffered object
});

作为一个注释,在preCallback上最好运行此代码,然后在完成后从中调用动画,无需添加此功能。