2013-05-16 32 views
0

我試圖動態顯示反彈並向前一球。 首先,球必須反彈X倍,在同一個地方,但隨後必須往前走反彈。jQuery的動畫2分的動作,相同的對象

BOUNCE:

$("#ball").animate({top:"-=5px"},150).animate({top:"+=5px"},150); 

MOVING:

$("#ball").animate({"left":"850px"},2800); 

什麼建議嗎?

+0

[這個問題] (http://stackoverflow.com/questions/10473572/e xecute-multiple-jquery-on-the-the-same-element-in-parallel)可能會有所幫助。 – Blazemonger

+0

彈跳球代碼是在這裏的另一個類似的問題:http://stackoverflow.com/questions/2344804/how-can-i-execute-multiple-simultaneous-jquery-effects – carrabino

回答

0

這裏有一個方法。讓球反彈X倍,我們可以創建一個遞歸函數,它接受的jQuery動畫隊列的優勢:

function bounce(n) { 
    if (n > 0) { 
     $("#ball").animate({top: "-=5px"}, 150) 
      .animate({top: "+=5px"}, 150, function() { 
       bounce(n-1); 
      }); 
    } 
}; 
bounce(3); 

得到它之後推出,並繼續反彈,我們需要使用.dequeue()在同時運行動畫一次:

$("#ball").animate({"left": "850px"}, 2800).dequeue(); 
bounce(10); 

現在,把它們結合在一起,創建一個特殊的回調函數,僅第十屆反彈後運行:

function bounce(n, callback) { 
    if (n > 0) { 
     $("#ball").animate({top: "-=5px"}, 150) 
      .animate({top: "+=5px"}, 150, function() { 
       bounce(n-1, callback); 
      }); 
    } else if (callback) { // might be undefined 
     callback(); 
    } 
}; 

bounce(3, function() { 
    $("#ball").animate({"left": "850px"}, 2800).dequeue(); 
    bounce(10); 
}); 

http://jsfiddle.net/mblase75/c72Qj/

+0

它工作!謝謝!萬一 – hanskait

1

這裏有一個小提琴,你想要什麼,你可以很容易地調整它:
http://jsfiddle.net/2LyWM/

$(document).ready(function(){ 

    $("#ball").queue(function() { 

     $(this).animate({top:'+=50px'}, { duration: 500, queue: true }); 
     $(this).animate({top:'0px'}, { duration: 500, queue: true }); 
     $(this).animate({top:'+=50px'}, { duration: 500, queue: true }); 
     $(this).animate({top:'0px'}, { duration: 500, queue: true }); 
     $(this).animate({top:'+=50px'}, { duration: 500, queue: true }); 
     $(this).animate({top:'0px'}, { duration: 500, queue: true }); 
     $(this).animate({top:'+=50px'}, { duration: 500, queue: true });   
     $(this).animate({left:'+=100px'}, { duration: 2500, queue: false }); 

     $.dequeue(this); 
    }); 

}); 

HTML

<div id="ball">ball</div> 

CSS

#ball{ 
    top: 0px; 
    left: 0px; 
    position: relative; 
} 
+0

你想知道,在「隊列:真正的」告訴了jQuery「排隊這個動畫」(即等到其他動畫已經開始之前完成)。最後一個動畫行(queue:false)告訴jquery立即運行動畫,這會給你想要的效果。此外,您可以將所有隊列=真實動畫(3,500)的持續時間加起來,這將是動畫運行的總時間。我將左側的動畫設置爲2500(早期1000毫秒)。 – carrabino