javascript - 如何在 for 循环的每次传递中增加动画延迟

标签 javascript jquery for-loop jquery-animate delay

首先,我创建了一个基本演示,展示了我现在拥有的东西 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 循环中,但没有运气。任何帮助都会很棒。

最佳答案

您可以将数组索引作为附加参数传递给您的 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 上绑定(bind)多个悬停事件处理程序并且必须维护 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

关于javascript - 如何在 for 循环的每次传递中增加动画延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14946197/

相关文章:

javascript - 如何延迟 Bodymovin 动画

javascript - 如果内联 SVG 在运行时插入到文档中,它可以在 HTML4 中工作吗?

javascript - 不通过 javascript 加载特定屏幕尺寸的所有链接并高级 java

javascript - 点击下面的一个div元素?

php - "self-referencing"表和数组

javascript - 在 Javascript 中循环一串数字

javascript - if/else 变量存在的简写

java - jquery.js 没有在 Tomcat 中加载

scala - Scala 中 for 循环加 2

javascript - 通过 for 循环扩充数组只保留最后一个对象?