2013-02-18 6 views
6

まず、私が現時点で持っているものの基本的なデモンストレーションを作成しましたhereforループの1回のパスごとにアニメーションの遅延を増やす方法

これは私が使用している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の遅延時間がそれぞれ次々にホバーすることですforループ内のsetTimeoutも運行はありません。どんな助けも素晴らしいだろう。

答えて

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

+0

素晴らしいソリューションです。ありがとう。 – Mimo

+0

@ user1846307もしあなたが興味があれば、私はまた別の解決法を追加しました。 –

+0

余計な情報をお寄せいただきありがとうございます。残念ながら、箱は私の生きている問題のデモであり、配列を使用する必要があります。しかし、私はon()関数を見たことがないので、将来はその関数を使うことにします。再度、感謝します。 – Mimo

関連する問題