JavaScript 和 jQuery : iterate through an array but wait for animations to finish

标签 javascript jquery jquery-animate loops

我有一个简单的示例,其中有几个框可以在屏幕上移动。在前一个盒子完成之前,每个盒子都不应移动。我有一个使用 .shift() 的工作解决方案,但我应该能够使用 for 循环和 $.each 来迭代它。有人知道如何让 for 和 $.each 工作吗?

fiddle here Shift 按钮按照我希望的方式工作。

谢谢。

JS:

boxes = [
  ['.box0', 'animate', [ {left: '200px' }, 1000 ] ],
  ['.box1', 'animate', [ {left: '200px' }, 1000 ] ],
  ['.box2', 'animate', [ {left: '200px' }, 1000 ] ],
  ['.box3', 'animate', [ {left: '200px' }, 1000 ] ],
  ['.box4', 'animate', [ {left: '200px' }, 1000 ] ],
  ['div', 'animate', [ {left: '0px' }, 1000 ] ]
];
$('.eachMethod').click(animEach);
$('.ifMethod').click(animFor);
$('.shiftMethod').click(animShift);
function animEach(){
  $.each(boxes, function(){
    $.fn[this[1]].apply($(this[0]), this[2]).promise().done();
  });
};
function animFor(){
  for (i=0; i < boxes.length; i++) {
    b=boxes[i];
    $.fn[b[1]].apply($(b[0]), b[2]).promise().done();
  }
};
function animShift(){
  b = boxes.shift();
  if (b) {
    $.fn[b[1]].apply($(b[0]), b[2]).promise().done(animShift);
  }
};​

HTML:

<ul>
  <li><button class='eachMethod'>$.each</button></li>
  <li><button class='ifMethod'>if</button></li>
  <li><button class='shiftMethod'>shift</button></li>
</ul>
<div class='box0'></div>
<div class='box1'></div>
<div class='box2'></div>
<div class='box3'></div>
<div class='box4'></div>​

CSS:

div{
 clear: both;   
 background-color: green;
 width: 40px;
 height: 40px;
 Position: relative;    
}
ul li {
  float: left;
}

最佳答案

animate() 是异步的,因此循环将在几毫秒内完成,几乎同时调用每个元素上的动画。当您使用循环时,您的 .promise().done() 没有执行任何操作。

使用 animShift() 的版本一次仅将动画应用于一个元素,并且由于下一次调用是在 done() 内,因此不会触发直到第一个动画完成

关于JavaScript 和 jQuery : iterate through an array but wait for animations to finish,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13551852/

相关文章:

javascript - 当我在 Firefox 中修改着色器时,Firefox Shader Editor 不工作

php - 创建一个在未填写时显示错误的联系表格? (验证)

html - 使用动画变换旋转地球 svg

JQuery 使用each() 获取准确的元素高度

javascript - 为什么我不能使用 Array.prototype.find 和 String.prototype.startsWith 作为过滤器?

javascript - 数据来自API,但不显示。 Angular 9 ABP 框架

javascript - 我想确保加载外部 HTML 后函数出现

jquery - 如何将 CSS 动画更改为 jquery animate() 代码?

jquery - 日期选择器更改表单提交上的日期格式

javascript - 使用 CSS 和 Javascript 的无限旋转动画