2014-08-29 62 views
0

簡單的問題,如何運行此jQuery反彈懸停在總是反彈下方。所以我不需要徘徊,每次都會彈跳。每次運行jQuery函數(在彈跳效果的情況下)

下面是代碼:

$(document).ready(function(){ 
     $(".button").hover(function(){ 
      $(".button img") 
      .animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) // first jump 
      .animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) // second jump 
      .animate({top:"-6px"}, 100).animate({top:"-4px"}, 100); // the last jump 
     }); 
    }); 
+0

使用'setInterval'定期運行的功能。 – Barmar 2014-08-29 01:55:40

回答

2

您應該使用setInterval和計時器=動畫總時間延遲

setInterval(function(){ 
    $(".button img") 
    .animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) // first jump 
    .animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) // second jump 
    .animate({top:"-6px"}, 100).animate({top:"-4px"}, 100); // the last jump 
},600); 

或遞歸函數

function bounce(){ 
    $(".button img") 
     .animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) 
     .animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) 
     .animate({top:"-6px"}, 100).animate({top:"-4px"}, 100,function(){ 
     bounce(); 
    }); 
} 
bounce(); 
0

這將不只是改變了2000年到你想要的(你的動畫結束後)的任意時間。

var timer = setInterval(function(){ 
    $(".button img") 
    .animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) // first jump 
    .animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) // second jump 
    .animate({top:"-6px"}, 100).animate({top:"-4px"}, 100); 
}, 2000); 

那麼如果你想讓它停下只是調用

clearInterval(timer); 
1

把反彈代碼的函數,而從最後一個動畫回調調用它,所以它會重新啓動:

function bounce_img(img) { 
    img.animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) // first jump 
     .animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) // second jump 
     .animate({top:"-6px"}, 100).animate({top:"-4px"}, 100, // last jump 
       function() {bounce_img(img);}); // restart 
} 

$(document).ready() { 
    $(".button img").each(function() { 
     bounce_img($(this)); 
    }); 
}); 
+0

更好的解決方案,然後setInterval IMO,+1 – epipav 2014-08-29 02:15:38

相關問題