在for循环Jquery/Javascript中设置延迟

Setting a delay whilst in a for loop Jquery/Javascript

本文关键字:设置 延迟 Javascript for 循环 Jquery      更新时间:2023-09-26

这里有点困惑,不确定是不是周一早上的忧郁!它只是不起作用:(

我想实现的是:

在每个元素中衰减,间隔设置为相对

我的HTML代码是(这些都用CSS隐藏)

    <div id="rpStage">
        <div class="rpItem" rel="500">
            <p>0</p>
        </div>
        <div class="rpItem" rel="4000">
            <p>1</p>
        </div>
        <div class="rpItem" rel="6000">
            <p>2</p>
        </div>
    </div>

还有我的javascript/jquery。

function fadeInrpItem (rpItem, rpDelayTime) {
    rpItem.stop().animate({"opacity" : 1}, 400);
    setInterval(rpDelayTime);
};
function startTheRp () {
        for(var index=0; index < $('.rpItem').length; index++) {
            var rpItem = $('.rpItem').eq(index);
            //Pull in our delay attribute from the div
            var rpDelayTime = rpItem.attr('rel');
            fadeInrpItem(rpItem, rpDelayTime);          
        }
};
$(document).ready(function(){
    startTheRp();
});

原始代码中的问题是使用setInterval的计时,因为您没有向它传递函数,所以它目前什么都不做。此外,原始代码使整个问题复杂化。

我认为这是你想要的

delayTime = 0 // initialise delayTime
$('.rpItem') // select all the items we want to work with
    .css({opacity:0}) // for testing - can be commented out
    .each(function(){ // loop through each item
      $this = $(this) // cahce reference of $(this) to improve performance
      delayTime = delayTime + parseInt($this.attr('rel')) // increment delayTime
      $this.data('delay',delayTime) // set current delayTime to item's data (so that asynchronous calls do not use global/updated version when they are called)
      $this // get reference to item as jQuery object
        .delay( $this.data('delay') ) // set the delay as the item's rel attribute
        .animate({"opacity" : 1}, 400) // fade in the item with duration 400
    })

它将选择所有的.rpItem(然后将不透明度设置为0进行测试),并循环通过它们。然后,通过参考$(this),我们可以单独对每个项目进行操作,将延迟设置为每个项目的rel属性,然后以400的持续时间制作动画。

试试这个:

$(document).ready(function(){
    $('.rpItem').each(function(){
        $(this).animate({"opacity" : 1}, $(this).attr('rel'));
    });
});

这将适用于visibility:hidden

setInterval函数的使用如下

function fadeInrpItem(rpItem, rpDelayTime) {
    setInterval(rpDelayTime) {
        rpItem.stop().animate({
            "opacity": 1
        }, 400);
    }
};