簡體   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