【问题标题】:How to increase the delay on animation on every pass of a for loop如何在每次通过 for 循环时增加动画延迟
【发布时间】:2013-02-03 11:13:33
【问题描述】:

首先,我创建了一个基本演示,说明我目前所拥有的 here

其次,这是我正在使用的 javascript。

var boxes = ["#one","#two","#three","#four"];

boxhover = function(a){
    $("#hover").hover(
        function(){
            $(a).stop(true).delay(250).animate({opacity:1});
        },
        function(){
            $(a).stop(true).delay(250).animate({opacity:0});
        }
    )
}

for(var i=0; i<boxes.length; i++)
{
    boxhover(boxes[i])
}

我希望实现的是让每个框一个接一个地悬停,延迟时间为 250。我尝试向动画功能添加延迟(如上所示)以及 setTimeout在 for 循环中,但没有运气。任何帮助都会很棒。

【问题讨论】:

    标签: javascript jquery for-loop jquery-animate delay


    【解决方案1】:

    您可以将数组索引作为附加参数传递给boxhover 函数,然后对延迟因子执行乘法运算。

    var boxes = ["#one","#two","#three","#four"];
    
    boxhover = function(a, i){
        $("#hover").hover(
            function(){
                $(a).stop(true).delay(250 * i).animate({opacity:1});
            },
            function(){
                $(a).stop(true).delay(250 * i).animate({opacity:0});
            }
        )
    }
    
    for(var i=0; i<boxes.length; i++)
    {
        boxhover(boxes[i], i)
    }
    

    jsfiddle

    替代解决方案:

    为避免在#hover 上绑定多个悬停事件处理程序并不得不维护一组 ID,您可以执行以下操作:

    $("#hover").on({
        'mouseenter': function(e) {
            // Animate the box set to visible
            animateBoxSet(1);
        },
        'mouseleave': function(e) {
            // Animate the box set to invisible
            animateBoxSet(0);
        }
    });
    
    function animateBoxSet(opacity) {
        // For each box
        $('.box').each(function (index, element) {
            // Set the delay based on the index in the set
            var delay = 250 * index;
            // Animate it the visibility after the delay
            $(element).stop(true).delay(delay).animate({
                'opacity': opacity
            });
        });
    }
    

    jsfiddle

    【讨论】:

    • @user1846307 如果您有兴趣,我还添加了替代解决方案。
    • 感谢您提供额外信息,不幸的是,这些盒子只是我现场问题中的一个演示,我需要使用一个数组。但我之前没有见过 on() 函数,所以我会考虑在未来使用它。再次感谢。
    猜你喜欢
    • 2013-12-12
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多