繁体   English   中英

.animate()的jQuery自定义回调

[英]jQuery Custom Callback for .animate()

我正在尝试为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
});

但是,当我运行此代码时,我的“ //做某事”不会触发。 我也尝试使用[Dave 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");

这将导致两个事件的两次触发类型均等于“动画”。 要使其在之前设置为animatebefore,在之后设置为animate,请替换. :

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

现在我们正确地获得animate:beforeanimate:after 现在我们知道我们的事件正在运行,让我们将其绑定到动画方法中。

$("#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
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM