html jQuery点击反弹效果无jQuery UI

xggvc2p6  于 2022-12-16  发布在  jQuery
关注(0)|答案(6)|浏览(113)

我找不到一个动画的解决方案,使一个div反弹,只使用jQuery动画。

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

我不希望使用jQuery UI或任何外部插件,比如Easing插件,在我的情况下,抖动效果也一样好,所以两者都可以。
这里是一个example,任何帮助将不胜感激!提前感谢

ki1q1bka

ki1q1bka1#

您可以简单地将元素上的一些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/

5ktev3wc

5ktev3wc2#

这个函数用于阻尼反弹。如果不加修改地使用代码,请确保给予反弹元素一个唯一的类。

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>
whlutmcx

whlutmcx3#

对于垂直反弹,您可以尝试以下操作:

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

8ljdwjyq4#

我使用这个简单的插件jQuery-Shake来摇动或反弹一个没有jQuery-UI的元素。

$('#elementToBounce').shake({direction: up, distance:10, speed: 75, times: 3})

小提琴:https://jsfiddle.net/ek7swb6y/3/

piwo6bdm

piwo6bdm5#

我通常使用jQuery animate。对于您的特定问题,它可以看起来像这样:
HTML:

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

中央支助组:

#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/

jaql4c8m

jaql4c8m6#

结合不同的答案,这就是我点击后的效果

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');

相关问题