2013-03-26 160 views
2

當我將鼠標放在它們上面時,我試圖在現有圖像上淡出圖像,而無需爲每個圖像重新編寫相同的功能。這是什麼正確的語法?

目前我有:

<script type="text/javascript"> 

    $(document).ready(function() { 

     $('.image').mouseenter(function() { //fade in hover image 
      $(this.getAttribute("name")).fadeIn(500); 
     });       
     $('.hoverimage').mouseout(function() { //fade out hover image 
      $(this).fadeOut(500); 
     }); 

    }); 

</script> 

... 
... 

<!--base images--> 
<img src="image1.png" class="image" name="hoverimage1"> 
<img src="image2.png" class="image" name="hoverimage2"> 
<img src="image3.png" class="image" name="hoverimage3"> 

<!--image to appear when hovering over--> 
<img src="image1_glow.png" class="hoverimage" id="hoverimage1"> 
<img src="image2_glow.png" class="hoverimage" id="hoverimage2"> 
<img src="image3_glow.png" class="hoverimage" id="hoverimage3"> 

假設CSS已經有這麼懸停圖像被放置在基本圖像的頂部。我的代碼試圖做的是:

  • 當鼠標進入的「image1.png」分區,它會得到name屬性「hoverimage1」
  • 然後消失在ID爲「hoverimage1」的元素通過基本上執行$('#hoverimage1「)。fadeIn(500);

但問題是name屬性沒有」#「,我不想寫」name =「#hoverimage1 「因爲這對身份證來說很混亂。現在我的函數執行$('hoverimage1「)。fadeIn(500);這是不正確的語法。

有人可以幫助我嗎?是否可以附加一個」#「到」$(this。 ?的getAttribute())」什麼

+0

+1不浪費時間創建jQuery對象來獲取屬性。 – 2013-03-26 22:59:52

回答

3

如果要在前面加上一個#,那麼你可以在連接字符串:

$('#' + this.name) 

但如果可能的話我會使用的元素索引對於這一點,:

$('.image').mouseenter(function() { 
     $('.other_images').eq($(this).index()).stop().fadeIn(500); 
    }).mouseout(function() { 
     $('.other_images').eq($(this).index()).stop().fadeOut(500); 
    }); 

這樣,您甚至不需要在父圖像的name屬性中編寫其他圖像的id

+0

我沒有真正遵循你的代碼的邏輯。 '$('。other_images')。eq($(this).index())'究竟是如何工作的?我看不出它是如何分辨出要淡入的懸停圖像。 – Windbrand 2013-03-26 23:22:20

+0

@Windbrand:'.eq(2)'選擇與選擇器匹配的第三張圖像。 '.index()'獲取選擇器中當前元素的索引,所以基本上當您單擊該元素集中的第一個圖像時,另一組元素中的第一個圖像就會生成動畫。 – Blender 2013-03-27 00:04:20

2

由於該屬性爲hoverimage1,因此該腳本正在尋找<hoverimage1>元素。您需要將#連接到開頭:$("#"+this.getAttribute("name"))