jQuery each() with a delay

前端 未结 5 2009
执念已碎
执念已碎 2021-02-07 08:33

So, I would like an element to fade in and wait half a second, then fade the next in etc...

My code:

$(\'.comment\').each(function() {                 
          


        
5条回答
  •  一向
    一向 (楼主)
    2021-02-07 09:07

    or using .next() and a callback function:

    // create a function to fade in the comment block
    function showit(item){
    
        // animate the fade effect (and any other required)
        item.animate({opacity:1},450,function(){
    
            // after completing the animation, call the
            // showit function with the next comment block
            showit(item.next('.comment'))
    
        })
    
    }
    
    // set the opacity of comment blocks to 0 and
    // select the first one, then call showit to
    // initialise animation loop
    showit( $('.comment').css({opacity:0}).eq(0) )
    

    Fiddle here: http://jsfiddle.net/rJnnZ/

    I think this is a better solution, because it waits until the previous animation is finished, before moving onto the next, rather than calculating the timer beforehand, which can become un-synchronised under heavy CPU usage, or various other circumstances.

提交回复
热议问题