jQuery Add then remove width to consecutive elements in a loop

别等时光非礼了梦想. 提交于 2020-01-07 08:26:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!