.animate()的jQuery自定义回调

jQuery Custom Callback for .animate()

本文关键字:自定义 回调 jQuery animate      更新时间:2023-09-26

我正在尝试为jQuery.animate()函数创建一个自定义回调。我仅限于jQuery 1.4.2,并基于此[Dan Switzer的文章][1]进行自定义调用

(function ($){
    var oldAnimate = $.fn.animate;
    $.fn.animate = function(){
        this.trigger('animate.before', arguments);
        var animateResult = oldAnimate.apply(this, arguments);
        this.trigger('animate.after', arguments);
        return animateResult;
    };
})(jQuery || {});
$('#ID').bind('animate.after', function (){ 
    //Do Something
});

但是,当我运行此代码时,我的"//做某事"不会触发。我也试着遵循[Davi Ward的文章][1],使用这个:

var oldAnimate = jQuery.animate;
jQuery.animate = function() {
    if (typeof animate.before === 'function')
    animate.before.apply(this, arguments);
    var animateResult = oldAnimate.apply(this, arguments);
    if (typeof animate.after === 'function')
    animate.after.apply(this, arguments);
    return animateResult;
};

我不确定哪里出了问题。

好的,所以您发现您的代码不起作用。第一步是简化它,并分别测试它的各个部分。让我们从事件开始。

$("#ID").bind("animate.before animate.after",function(e){
   console.log(e.type); 
}).trigger("animate.before").trigger("animate.after");

这将导致两次触发类型都等于"animate"的两个事件。要使其显示animatebefore和animateafter,请将.替换为:

$("#ID").bind("animate:before animate:after",function(e){
   console.log(e.type); 
}).trigger("animate:before").trigger("animate:after");

现在我们正确地得到了animate:beforeanimate:after。现在我们知道我们的事件正在工作,让我们将其绑定到animate方法中。

$("#ID").bind("animate:before animate:after",function(e){
   console.log(e.type); 
});
var oldanim = $.fn.animate;
$.fn.animate = function() {
    this.trigger("animate:before");
    oldanim.apply(this,arguments);
    this.trigger("animate:after");
};
$("#ID").animate({"width":"200px"},2000,function(){
    console.log("animation complete");
});

它有效!!!然而,你很快就会注意到after事件发生的时间比它应该发生的要晚。这是因为animate方法使用setTimeouts以异步方式执行,因此代码会继续运行。至于如何解决这个问题,我还没有任何建议,因为我们没有将对象推迟到1.5。您可以覆盖整个函数,但必须考虑到它可以通过两种不同的方式连接。

complete选项怎么样?我想这在jQuery 1.4.1 中是可用的

$('#id').animate({
    properties..
}, {
    complete: function() {
        // doStuff
    }
});