2012-04-28 76 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>