【问题标题】:How to stop an .each .animate loop function in jQuery如何在 jQuery 中停止 .each .animate 循环函数
【发布时间】:2019-03-29 07:43:24
【问题描述】:

我尝试移动一组不同的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>

【问题讨论】:

  • 添加 .stop() 到结尾
  • 是的...我刚刚找到它

标签: javascript jquery function jquery-animate each


【解决方案1】:

你可以在末尾添加.stop()

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-01-20
  • 2016-07-26
  • 2012-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
相关资源
最近更新 更多