jQuery each() with a delay

前端 未结 5 2006
执念已碎
执念已碎 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:06

    This function will iterate through every element in the collection (in this example $comments) and fade in all of them. Every animation will start when the previous one has finished.

    var $comments=$('.comment');
    
    (function fadeIterator($collection, index) {
        $collection.eq(index).fadeIn(1000, function () {
            fadeIterator($collection, index++);
        });
    }($comments, 0));
    

    jsFiddle Demo

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-07 09:13

    try something like this

    $(this).find('#results').children().each(function(index){
            $(this).delay(500 * index).slideDown(500);
    })
    
    0 讨论(0)
  • 2021-02-07 09:27

    Or, something like this:

    $.each($('.comment'), function(i, el){
    
        $(el).css({'opacity':0});
    
        setTimeout(function(){
           $(el).animate({
            'opacity':1.0
           }, 450);
        },500 + ( i * 500 ));
    
    });
    

    demo => http://jsfiddle.net/steweb/9uS56/

    0 讨论(0)
  • 2021-02-07 09:31

    Try this out:

    var time = 500;
    $('.comment').each(function() {                 
         var $this  = $(this);
        function delayed() {
             $this.css({'opacity':0.0}).animate({
                        'opacity':1.0
                    }, 450);
         }
        setTimeout( delayed , time );
        time += 500;
     });
    
    0 讨论(0)
提交回复
热议问题