开发者

jQuery each() with a delay

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() {                 
                    $(this).css({'opacity':0.0}).animate({
                        'opacity':1.0
      开发者_运维问答              }, 450).delay(500);
                });

I'm obviously doing something really silly.... (I hope)... My question is: Is this even possible? if not - can anyone point me in the right direction?

Thanking you!


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/


try something like this

$(this).find('#results').children().each(function(index){
        $(this).delay(500 * index).slideDown(500);
})


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;
 });


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜