2012-09-15 21 views
1

我有這樣的代碼:jQuery動畫可以通過編程鏈接嗎?

jQuery('#flash').animate({opacity: 0.35}, 200) 
       .animate({opacity: 0}, 200) 
       .animate({opacity: 0.35}, 200) 
       .animate({opacity: 0}, 200) 
       .animate({opacity: 0.35}, 200) 
       .animate({opacity: 0}, 600) 

,我沒有決定多少次,我想它的狀態改變。有沒有辦法以編程方式鏈接動畫,而不必通過編輯動畫鏈來添加/刪除鏈元素?

回答

2

不,你不能鏈的動畫,而無需編輯動畫隊列。如果你想鏈上的變量,但次數有限的,你可以很容易地用循環做:

var flash = $("#flash"); 
for (var i=0; i<n; i++) 
    flash.animate({opacity: 0.35}, 200).animate({opacity: 0}, 200); 

如果你想要一個死循環,或者一個當條件是在未來應驗停止,要勾上的動畫隊列的回調,重新啓動功能:

var flash = $("#flash"); 
function anim() { 
    // if (condition) 
    flash.animate({opacity: 0.35}, 200).animate({opacity: 0}, 200, anim); 
              // call "recursively": ^^^^ 
} 
anim(); 
1

如果您正在尋找,您可以使用循環鏈接動畫。

var $flash = jQuery('#flash'), i; 

for (i = 0; i < 10; i++) { 
    $flash = $flash.animate({opacity: 0.35}, 200) 
        .animate({opacity: 0}, 200); 
} 
2

如果我理解正確,你只需要一個FOR循環:

function animate_n_times(n) { 
    var flash = $('#flash'); 
    for(var i=0;i<n;i++) { 
     flash.animate({opacity: 0.35}, 200) 
      .animate({opacity: 0}, 200); 
    } 

} 

然後叫這樣的:

animate_n_times(3); 
0

有一個較短的替代,使用擴展jquery-timing

動畫一個給定的次數:

$('#flash').repeat().animate({opacity:0.35}, 200) 
    .animate({opacity:0}, 200).until(10); 

由於無限循環:

$('#flash').repeat().animate({opacity:0.35},200).animate({opacity:0},200,$); 

詳情見的.repeat().until(count),並.animate(…,$)的API。