我有一个简单的示例,其中有几个框可以在屏幕上移动。在前一个盒子完成之前,每个盒子都不应移动。我有一个使用 .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/