2012-01-09 51 views
38

如果選擇元素的類或者集合使用jQuery動畫:

$('.myElems').animate({....}); 

然後還要使用回調函數,你結束了一個很多不必要的animate()來電。

var i=1; 
$('.myElems').animate({width:'200px'}, 200, function(){ 
    //do something else 
    $('#someOtherElem').animate({opacity:'1'}, 300, function(){   
     if (i>1) console.log('the '+i+'-th waste of resources just finished wasting your resources'); 
     i++; 
    }); 
}); 

可以說這只是糟糕的代碼和/或設計 - 但有什麼我可以做,既避免了使用回調有很多animate()調用其中只有一個,並且具有執行不必要的回調的負荷和擰我的代碼/預期的行爲?

理想情況下,我只能編寫一個只能運行一次的「一次性」回調 - 否則可能有一種有效的方法來測試某些東西是否已被jQuery動畫化?

例如:http://jsfiddle.net/uzSE6/(警告 - 這將顯示一個警報框的負載)。

+0

定義一個標誌變量,可以在文件範圍或某處通過'animate()'訪問。在'$(「#someOtherElem')。animate()'調用之前檢查它並將其設置在它的主體中,以便下次不會調用$(」#someOtherElem')。animate()「。 – fardjad 2012-01-09 18:31:08

回答

99

您可以使用when像:

$.when($('.myElems').animate({width: 200}, 200)).then(function() { 
    console.log('foo'); 
}); 

http://jsfiddle.net/tyqZq/

Alterna te版本:

$('.myElems').animate({width: 200}, 200).promise().done(function() { 
    console.log('foo'); 
}); 
+7

我喜歡這個。我非常喜歡這個。我不知道這些函數,這幫助了很多:) – jammypeach 2012-01-10 09:04:05

+5

+1我發現它非常有用''('html,body')。animate(...) – Alvaro 2014-10-15 16:15:32

2

您可以創建一個變量來阻止第二+回調...

var i=1; 
$('.myElems').animate({width:'200px'}, 200, function(){ 
    //do something else 
    $('#someOtherElem').animate({opacity:'1'}, 300, function(){   
     if (i>1) return; 
     else 
     { 
      console.log('the '+i+'-th waste of resources just finished wasting your resources'); 
      i++; 
     } 
    }); 
}); 

這隻會爲每個後續回調閃光一次將被取消:)

+3

我建議使用不同於'i'的變量名,這是常見的,可能會被意外覆蓋,並且爲了清晰起見而將其設置爲「true」或「false」。 – Blazemonger 2012-01-09 18:32:07

+1

^當然,但我用我,因爲它已經在示例代碼中可用,我只是用它稍微調整。從清晰的角度來看,像'callbackdone'設置爲布爾值會更有意義。 – bardiir 2012-01-09 18:34:53

相關問題