问题
OK so once a page has finished loading, I want to add a width to a group of elements, one after the other in a loop.
Example:
<div id="container-wrap">
<div id="container"></div>
<div id="container"></div>
<div id="container"></div>
<div id="container"></div>
<div id="container"></div>
</div>
So it would add the width to the first element, then remove then move on to the second element, so on and so forth.
Then once it gets to the last one, it starts over.
How would I do that?
回答1:
Edited : my idea with deferreds didnt work , but in cycle you can add .delay(..)
to delay animations on different elements accordingly
see jsfiddle http://jsfiddle.net/vittore/Yzpft/
var containers = $('#container-wrap').find('.container')
containers.each(function(ind,el) {
$(el).delay(800 * ind)
.animate({'width': '400px'}, 400)
.animate({'width': '100px'}, 400)
})
Now if you need to constanly do it without delay and your number of element is constant you can use following code
var containers = $('#container-wrap').find('.container')
, length = containers.length
, interval = 800 * length
, intervalVar = null
function animate() {
containers.each(function(ind,el) {
$(el).delay(800 * ind)
.animate({'width': '400px'}, 400)
.animate({'width': '100px'}, 400)
})
})
intervalVar = setInterval(animate, interval)
... and whenever you need to stop it
clearInterval(intervalVar)
来源:https://stackoverflow.com/questions/16430764/jquery-add-then-remove-width-to-consecutive-elements-in-a-loop