点击时使用jQuery实现弹跳效果,无需使用jQuery UI

10

我无法找到一个使用jQuery动画让一个div反弹的解决方案。类似以下代码是不起作用的:

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

我希望不使用jQuery UI或任何外部插件,例如缓动插件。在我的情况下,摆动效果也很好,所以两种方法都可以。

这里有一个示例,非常感谢任何帮助!提前致谢。


我仍然建议只使用jQueryUI。我也曾犹豫过使用jQueryUI,但是由于您可以选择要在下载中包含其哪些组件,因此您可以只选择弹跳效果而不包括其他任何内容,所以js + css文件将非常小,约为15kb。 - tObi
6个回答

29

您可以在元素上简单地链式调用一些 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/


抱歉,我忘记保存这个代码片段了。现在请再次检查。 - Will Demaine
对于那些无法使此功能正常工作的人,请确保没有应用于您尝试弹跳的元素的CSS过渡属性。这可能会干扰,因为我们在这里操作的是CSS属性。 - designcise
我们如何通过按钮停止此函数的弹跳? - Hassan Taleb

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() {
 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>


1

如果您想要实现垂直弹跳,可以尝试以下方法:

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"
 })
}

easeOutBounce 需要 jQuery Ui。 - Sparkup
在jQuery UI中,您可以直接使用shake。 - tObi

1
我使用这个简单的插件 jQuery-Shake 来抖动或弹跳一个元素,而无需使用 jQuery-UI。
$('#elementToBounce').shake({direction: up, distance:10, speed: 75, times: 3})

代码演示: https://jsfiddle.net/ek7swb6y/3/


太棒了!对我来说运行良好。 - LondonGuy

0

结合不同的答案,这是我在点击后所使用的方法

let el = $('.bounce-me');
for (var i = 1; i <= 2; i++) {
  el.animate({ 'margin-top': 15 }, 'fast').animate(
    { 'margin-top': -15 },
    'fast'
  );
}
el.animate({ 'margin-top': 0 }, 'fast');

0
我通常使用jQuery的动画效果。针对您的具体问题,代码如下:
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");
     }
});

这里有一个可用的 fiddle:http://jsfiddle.net/5xz29fet/1/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接