2012-04-28 73 views
7

我找不到一個動畫的解決方案,使一個div反彈,只使用jQuery動畫。類似的東西不起作用:jQuery彈跳效果點擊沒有jQuery UI

$("#bounce").click(function() { 
    $(this).effect("bounce", { 
     times: 3 
    }, 300); 
});.​ 

我不希望使用jQuery UI或任何外部插件,如緩動。在我的情況下襬動效果會非常好,所以要麼都行。

這是一個example,任何幫助將不勝感激!在此先感謝

+0

我還是建議只使用jQueryUI的。我也猶豫使用jQueryUI,但你可以選擇你想要在你的下載中包含哪些組件,你可以選擇反彈和其他任何東西,所以js + css文件將相當小〜15kb – tObi 2014-08-08 15:41:12

回答

18

你可以簡單地鏈在一起的一些animate調用的元素,像這樣:

$("#bounce").click(function() { 
    doBounce($(this), 3, '10px', 300); 
}); 


function doBounce(element, times, distance, speed) { 
    for(var i = 0; i < times; i++) { 
     element.animate({marginTop: '-='+distance}, speed) 
      .animate({marginTop: '+='+distance}, speed); 
    }   
} 

工作例如:http://jsfiddle.net/Willyham/AY5aL/

+1

這個例子似乎沒有工作 – jacktheripper 2012-04-28 13:47:01

+0

對不起,我忘了保存小提琴。現在再檢查一次。 – 2012-04-28 13:51:39

+0

對於那些無法完成此工作的人,請確保沒有將CSS轉換屬性應用於您嘗試反彈的元素。它可能會干擾,因爲它是我們在這裏操作的CSS屬性。 – designcise 2014-01-07 01:29:53

0

對於垂直彈跳,你可以嘗試這樣的事:

function bounce(element, distance, speed){ 
var bounce_margin_top = $(element).css("margin-top") 
$(element).css("margin-top", "-="+distance) 

$(element).show().fadeIn(200).animate({ 
    "margin-top": bounce_margin_top 
}, { 
    duration: speed, 
    easing: "easeOutBounce" 
}) 
} 
+0

'easeOutBounce'需要jQuery Ui。 – Sparkup 2014-04-07 23:07:23

+0

和jQuery Ui中,你可以使用搖 – tObi 2014-08-08 15:42:08

0

我通常使用jQuery animate。爲了您的具體問題,它可能是這樣的:

的HTML:

<div id="bounce"></div> 

的CSS:

#bounce { 
height:50px; 
width:50px; 
background:#333; 
margin-top:50px; 
position:relative; 
} 

最後,jQuery的:

$("#bounce").click(function() { 
for (var i=1; i<=3; i++) { 
$(this).animate({top: 30},"slow"); 
$(this).animate({top: 0},"slow"); 
    } 
}); 

這裏是一個工作小提琴:http://jsfiddle.net/5xz29fet/1/

4

使用此功能進行衰減反彈。如果在不改變的情況下使用代碼,一定要給彈跳元素一個獨特的類。

var getAttention = function(elementClass,initialDistance, times, damping) { 
 
    for(var i=1; i<=times; i++){ 
 
     var an = Math.pow(-1,i)*initialDistance/(i*damping); 
 
     $('.'+elementClass).animate({'top':an},100); 
 
    } 
 
    $('.'+elementClass).animate({'top':0},100); 
 
} 
 

 
$("#bounce").click(function() { 
 
\t getAttention("bounce", 50, 10, 1.2); 
 
});
#bounce { 
 
    height:50px; 
 
    width:50px; 
 
    background:#f00; 
 
    margin-top:50px; 
 
    position:relative; 
 
    border-radius: 50px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="bounce" class="bounce"></div>