6

First I've created a basic demonstration of what I have at the moment here.

Second this is the javascript I'm using.

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

What I'm hoping to achieve is to have each box hover one after the each other with a delay time of 250. I've tried adding a delay to the animation function (as you can see above) and also a setTimeout in the for loop, but no luck. Any help would be great.

4

1 に答える 1

3

配列インデックスを追加パラメーターとして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

于 2013-02-18T22:18:19.030 に答える