2013-05-09 42 views
0

試圖一次只顯示一個元素使用每個函數,但不知道如何獲得與第一個項目相關聯的匹配項目,以便您將鼠標懸停在第一個「hoverMe」時,它只顯示第一個showMe和所以對使用每種方法獨立顯示各個元素

這是我到目前爲止,我認爲我可以做到這一點非常混亂的方式,但不知道是否有一個乾淨的方式來做到這一點。

http://jsfiddle.net/Pm2vP/

<p class="hoverMe">Hover me<span class="showMe">show me</span></p> 
<p class="hoverMe">Hover me<span class="showMe">show me</span></p> 
<p class="hoverMe">Hover me<span class="showMe">show me</span></p> 

$('.showMe').hide(); 

$(".hoverMe").each(function(){ 
    $(this).hover(
    function() { 
     $(".showMe").fadeIn(); 
    }, 
    function() { 
     $(".showMe").fadeOut(); 
    } 
); 
}); 

回答

1

this關鍵字將引用函數內部當前懸停的元素,並將其作爲在選擇範圍內,您只能選擇當前懸停的段落內的跨度。

.hover().on('mouseenter mouseleave'的快捷方式,我發現它更容易直接使用,並且fadeToggle()將切換衰落效果。

$('.showMe').hide(); 

$(".hoverMe").on('mouseenter mouseleave', function() { 
     $(".showMe", this).fadeToggle(); 
}); 

FIDDLE

編輯:

爲了確保衰落切換的正確(這幾乎是一個問題),你可以創建自己的切換功能:

$('.showMe').hide(); 

$(".hoverMe").on('mouseenter mouseleave', function(e) { 
     $(".showMe", this)[e.type=='mouseenter'?'fadeIn':'fadeOut'](); 
}); 
+0

啊,我覺得我最喜歡這個。它非常乾淨。我正在閱讀.on方法和fadeToggle,但沒有意識到這些。謝謝。 – lukasz 2013-05-09 22:33:01

+0

有一件事我會對這種方法持謹慎態度,即褪色與mouseenter/mouseleave狀態不同步。在正確的情況下,您可能會意外地使它在mouseleave上可見並且在mouseenter上不可見。只是要小心。 – Corion 2013-05-11 18:26:27

+1

@Corion - 比較容易解決,請參閱我的編輯。 – adeneo 2013-05-11 18:56:34

0

我d建議:

$('.showMe').hide(); 

$('.hoverMe').on('mouseenter mouseleave', function(e){ 
    // looks within the hovered-over element: 
    $(this) 
     // to find the '.showMe' element 
     .find('.showMe') 
     // stops all currently-running animations 
     .stop(true, true) 
     // fades the discovered '.showMe' element(s) in, or out 
     // depending on whether the mouse entered, or left, the '.hoverMe' element    
     .fadeToggle(e.type == 'mouseenter'); 
}); 

JS Fiddle demo

儘管如此,使用jQuery 1.9(與原來的演示不同,它使用1.6.4)。

但是,如果你想留下wtih的jQuery 1.6.4,您可以使用delegate(),雖然這是一個有點難看,可惜的是:

$('.showMe').hide(); 

$('.hoverMe').parent().delegate('.hoverMe', 'mouseenter mouseleave', function(e){ 
    $(this).find('.showMe').stop(true, true).fadeToggle(e.type == 'mouseenter'); 
}); 

JS Fiddle demo

參考文獻:

+0

我並沒有堅持1.6,它只是目前正在使用的項目。絕對能夠升級。寧願更清晰的語法。我現在就試試這個。 – lukasz 2013-05-09 22:29:40

0
$('.showMe').hide(); 
$(".hoverMe").mouseover(function(){ 
$('.showMe').fadeOut(); 
$(this).find(".showMe").fadeIn(); 

}); 
0

對於hoverMe類的每個項目,這些代碼中找到與showMe類懸停項目的孩子們,使他們fadeIn()和​​。

$(".hoverMe").each(function(){ 
    $(this).hover(
    function() { 
     $(this).children(".showMe").fadeIn(); 
    }, 
    function() { 
     $(this).children(".showMe").fadeOut(); 
    } 
); 
});