jQuery each()有一个延迟

时间:2011-06-15 15:14:16

标签: javascript jquery

所以,我想要一个元素淡入并等待半秒钟,然后淡出下一个等等......

我的代码:

$('.comment').each(function() {                 
                    $(this).css({'opacity':0.0}).animate({
                        'opacity':1.0
                    }, 450).delay(500);
                });

我显然做了一件非常愚蠢的事......(我希望)......我的问题是:这甚至可能吗?如果没有 - 有人能指出我正确的方向吗?

感谢你!

5 个答案:

答案 0 :(得分:38)

或者,像这样:

$.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/

答案 1 :(得分:12)

尝试这样的事情

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

答案 2 :(得分:5)

试试这个:

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

答案 3 :(得分:3)

此函数将遍历集合中的每个元素(在此示例中为$comments)并淡入所有元素。每个动画都将在前一个动画完成时开始。

var $comments=$('.comment');

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

jsFiddle Demo

答案 4 :(得分:3)

或使用.next()和回调函数:

// 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) )

在这里小提琴:http://jsfiddle.net/rJnnZ/

我认为这是一个更好的解决方案,因为它会等到上一个动画结束,然后再转到下一个动画,而不是事先计算定时器,这可能会在CPU使用率过高或其他各种情况下变得不同步。