2013-10-03 95 views
0

我需要定位多個div元素。他們都需要採取同樣的行動。他們基本上需要放大和縮小。如何使用for循環來定位多個div元素?

如何將我的循環變量傳遞給jquery和gsap?

for (var sca = 1; sca<=12; sca++) { 
    $("#sc"+sca).mouseover(function() { 
    TweenLite.to("sc"+sca, .5, {css:{ scale:1.3 }, ease:Back.easeOut}); 
    $("#sc"+sca).css("z-index","100"); 
    }) 
    .mouseout(function() { 
    TweenLite.to(sc1, .5, {css:{ scale:1 }, ease:Back.easeIn}); 
    $("#sc"+sca).css("z-index","1"); 
    }); 
} 
+0

給你的HTML代碼也。 – dev

回答

4

給所有div元素的同一類,那麼你可以在使用類選擇,同時附上相同的事件處理程序,所有的人,而不必循環。事情是這樣的:

$('.myClass') 
    .mouseover(function() { 
     TweenLite.to(this, .5, { css: { scale: 1.3 }, ease: Back.easeOut }); 
     $(this).css("z-index", "100"); 
    }) 
    .mouseout(function() { 
     TweenLite.to(this, .5, { css: { scale: 1 }, ease: Back.easeIn }); 
     $(this).css("z-index","1"); 
    }); 

另外,我不知道爲什麼你使用TweenLite當jQuery的動畫已經建成?

+1

正如@ rorymccrossan所說,這可能會導致冗餘代碼,因爲包含jquery動畫方法並且效率高達 – Stphane

+0

謝謝Rory。在這種情況下,這是我所需要的。 – user2838405

+0

當我使用tweenLite時,我使用了tweenLite,所以我已經習慣了它,並在網站的其他部分使用它。 – user2838405

0

不要使用一個循環,而不是事件處理程序綁定到一個ID爲「SC」開頭的所有元素,然後使用參考實際元素的函數中:

$('[id^="sc"]').mouseover(function() { 
    TweenLite.to(this.id, .5, {css:{scale:1.3}, ease:Back.easeOut}); 
    $(this).css("z-index","100"); 
    }) 
    .mouseout(function() { 
    TweenLite.to(this.id, .5, {css:{scale:1}, ease:Back.easeIn}); 
    $(this).css("z-index","1"); 
}); 

或者,如Rory建議,改爲使用類(類選擇器會稍微好一些)。

如果你絕對使用循環(你不這樣做,如上文所示),那麼你需要創建一個保存的sca該次迭代值封閉:

for(var sca = 1; sca <= 12; sca++) { 
    (function(sca) { 
     $("#sc"+sca).mouseover(function() { 
      TweenLite.to("sc"+sca, .5, {css:{scale:1.3}, ease:Back.easeOut}); 
      $("#sc"+sca).css("z-index","100"); 
     }) 
     .mouseout(function() { 
      TweenLite.to("sc" + sca, .5, {css:{scale:1}, ease:Back.easeIn}); 
      $("#sc"+sca).css("z-index","1"); 
     }); 
    })(sca); 
} 
0

您可以將一個事件處理程序作爲委託事件附加到第一個共同祖先。如果你有很多div放入你的文檔(更好地附加處理程序到每個div),這是一個性能問題。

舉個例子

// Delegated event 
    $('#commonAncestorID') 
     .on('mouseover','.divClass', function() { 
      TweenLite.to(this, .5, { css: { scale: 1.3 }, ease: Back.easeOut }); 
      $(this).css("z-index", "100"); 
     }) 
     .on('mouseout','.divClass', function() { 
      TweenLite.to(this, .5, { css: { scale: 1 }, ease: Back.easeIn }); 
      $(this).css("z-index","1"); 
     }); 

查看文檔here

+0

另外,任何將在稍後通過js在此相同容器中追加的div也會對mouseover/mouseout事件產生影響! – Stphane

2
$(document).ready(function() { 
     $('.fooDiv').mouseover(function() { 
      TweenLite.to(this, .5, { css: { scale: 1.3 }, ease: Back.easeOut }); 
      $(this).css("z-index", "100"); 
     }) 
     .mouseout(function() { 
      TweenLite.to('sc1', .5, { css: { scale: 1 }, ease: Back.easeIn }); 
      $(this).css("z-index", "1"); 
     }); 
    }); 
相關問題