简体   繁体   English

jQuery动画创建的元素

[英]Jquery animate created element

I made div, if i click on it, jquery makes bullet and that element is animated. 我做了div,如果我单击它,jquery会生成子弹,并且该元素会设置为动画。 This is code: 这是代码:

$('.square').click(function() {

$('<div class="bullet"></div>').appendTo($('body')).animate({
    'margin-top': 554
  }, 2000, function() {
$(this).remove();
  });
});

It works properly when I'm not clicking second time on div before animation is done. 当我在动画完成前没有第二次单击div时,它可以正常工作。 If i do this, my second "bullet" starts animation from position of first. 如果这样做,我的第二个“项目符号”将从第一个位置开始播放动画。 How to fix that? 如何解决? Thank's for help :) 感谢帮助 :)

UPDATE## Here's the jsfiddle with problem: https://jsfiddle.net/2ghj1x45/ 更新##这是有问题的jsfiddle: https ://jsfiddle.net/2ghj1x45/

Why not timeout the click function with a variable: 为什么不使用变量使click函数超时:

var animating = false;
$('.square').click(function() {

   if(!animating) {
      animating = true;
      setTimeout(function() {
          animating = false;
      }, 2000);

      $('<div class="bullet"></div>').appendTo($('body')).animate({
          'margin-top': 554
        }, 2000, function() {
           $(this).remove();
      });            
    }
});

EDIT: 编辑:

Updated JSfiddle 更新了JSfiddle

it's because the elements all have a size because they aren't positioned absolutely so each bullet div you add has display block, so will get it's own line where it's height is bullet size + margin top , which increases as it's animated. 这是因为所有元素都具有一定的尺寸,因为它们的位置不是绝对的,因此添加的每个子弹div都有显示块,因此将获得其自己的行,其高度为子弹尺寸+边距top,随着动画的增加而增加。 try instead using position absolute so the bullet div doesn't affect the layout of any other div 尝试改为使用绝对位置,以便项目符号div不会影响任何其他div的布局

like so 像这样

$(bullet).animate({ top: value });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM