如何在jQuery中停止.each .animate循环函数

时间:2018-10-24 19:33:51

标签: javascript jquery function jquery-animate each

我尝试移动一组不同的div,为此我做了function在空间中进行无限移动。现在,我想将不同的div放在某种网格中进行分类。它有时会运行,但不会停止function,并且在放置每个div时,它会继续移动。 我不想要的(不使用诸如Particle.js之类的库)是使其连续移动,但是当我单击时,它立即停止div并从其位置运行到网格,并且在第二次单击时,它从网格到该功能。

I write it on this jsFiddle

这是Jquery:

$(document).ready(function(){

function move() {
    $('div').each(function(){
      var top = $(this).css('top');
      var left = $(this).css('left');
      var topEnd = $(this).data('top-end');
      var leftEnd = $(this).data('left-end');
      $(this).animate({
          left: leftEnd,
          top: topEnd
      }, 3000).animate({
          left: left,
          top: top
      }, 3000,move);
     }
)}
move();

$('button').click(function(){
  $('div').each(function(){
            var position = $(this).position();
    var gridTop = $(this).data('grid-top');
    var gridLeft = $(this).data('grid-left');
    var topEnd = $(this).data('top-end');
    var leftEnd = $(this).data('left-end');
    if(position.top == gridTop ){
      $(this).animate({
        left: leftEnd,
        top: topEnd
      }, 2000);
    } else {
      $(this).animate({
        left: gridLeft,
        top: gridTop
      }, 2000);
    }
  });
});

});

这里是html:

<button>click moi</button>
<div data-grid-left="10px" data-grid-top="130px" data-left-end="250px" data-top-end="250px" style="background:green;left:-50px;"></div>
<div data-grid-left="130px" data-grid-top="10px" data-left-end="350px" data-top-end="-50px" style="background:red;top:200px;left:-200px;"></div>
<div data-grid-left="130px" data-grid-top="130px" data-left-end="500px" data-top-end="100px" style="background:blue;top:400px;left:-100px;"></div>

1 个答案:

答案 0 :(得分:0)

您可以在

的末尾添加.stop()

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