简体   繁体   中英

Jquery animate created element

I made div, if i click on it, jquery makes bullet and that element is animated. 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. 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/

Why not timeout the click function with a variable:

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

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. try instead using position absolute so the bullet div doesn't affect the layout of any other div

like so

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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