2011-05-24 83 views
11

我有以下的jQuery:如何等待一個jQuery動畫在下一個動畫開始之前完成?

$("#div1").animate({ width: '160' }, 200).animate({ width: 'toggle' }, 300); 
$("#div2").animate({ width: 'toggle' }, 300).animate({ width: '150' }, 200); 

我的問題是,無論是發生在同一時間。我希望div2動畫在第一個動畫完成時開始。我試過下面的方法,但它做同樣的事情:

$("#div1").animate({ width: '160' }, 200).animate({ width: 'toggle' }, 300, ShowDiv()); 
.... 
function ShowDiv(){ 
    $("#div2").animate({ width: 'toggle' }, 300).animate({ width: '150' }, 200); 
} 

我怎樣才能讓它等待第一個完成?

回答

21

http://api.jquery.com/animate/

有生有一個 「完整」 的功能。您應該將第二個動畫放在第一個動畫的完整功能中。

編輯:例如http://jsfiddle.net/xgJns/

$("#div1").animate({opacity:.1},1000,function(){ 
    $("#div2").animate({opacity:.1},1000);  
});​ 
+0

這不就是我在我的第二個例子中做什麼? – 2011-05-24 20:44:33

+1

你的第二個例子其實很接近。在第一行中從'ShowDiv'中刪除'()'。你正在調用這個函數而不是傳遞它。 – 2011-05-24 20:48:27

+0

gah!謝謝!如果我需要,我會如何傳遞一個參數? – 2011-05-24 20:51:57

1

可以傳遞函數作爲參數傳遞給animate(..)功能在動畫完成後,其被調用。像這樣:

$('#div1').animate({ 
    width: 160 
}, 200, function() { 
    // Handle completion of this animation 
}); 

下面的例子更清楚地解釋了參數。

var options = { }, 
    duration = 200, 
    handler = function() { 
     alert('Done animating'); 
    }; 

$('#id-of-element').animate(options, duration, handler); 
1

不要使用超時,請使用完整的回調。

$("#div1").animate({ width: '160' }, 200).animate({ width: 'toggle' }, 300, function(){ 

    $("#div2").animate({ width: 'toggle' }, 300).animate({ width: '150' }, 200); 

}); 
1

繼什麼kingjiv說,你應該使用complete回調鏈這些動畫。在第二個例子中,你幾乎已經有了它,除非你用括號跟着它執行你的ShowDiv回調。將其設置爲ShowDiv而不是ShowDiv(),它應該可以工作。

mcgrailm的回覆(貼在我寫這篇文章時)實際上是同樣的事情,只使用匿名函數進行回調。

0
$("#div1").animate({ width: '160' }, 200).animate({ width: 'toggle' }, 300, function() { 
$("#div2").animate({ width: 'toggle' }, 300).animate({ width: '150' }, 200); }); 

這對我的作品。我不知道爲什麼你的原始代碼不起作用。也許它需要在匿名函數中存在?

相關問題