2011-04-11 157 views
2

假設,我有以下HTML:選擇元素的父元素不具有特定的類

<ul class="topnav"> 
    <li class=""><a href="/">Page 1</a></li> 
    <li class=""><a href="/Page2/">Page 2</a></li> 
    <li class=""><a href="/Page3/">Page 3</a></li> 
    <li class=""><a href="/Page4/">Page 4</a></li> 
    <li class=""><a href="/Page5/">Page 5</a></li> 
    <li class="active"><a href="/Page6/">Page 6</a></li> 
</ul> 

當鼠標離開LI元件,它是假設改變字體的顏色回到灰色除了父元素LI的類值爲「active」的A元素。

下面是jQuery代碼我想:(該「鼠標離開」功能無法正常工作)

 $(".top_nav li a").mouseenter(
      function() { 
       $(this).stop().animate({'color': '#ffffff'}, 'slow'); 
     }); 

     $(".top_nav li a").mouseleave(
      function() { 
       $(this).parent().not(".active").stop().animate({'color': '#a5acb2'}, 'slow'); 
     }); 

回答

2

$(this).parent()選擇li元件和所有其他功能應用到這一個不是到a元件。

你可以這樣做:

$(this).not(".active > a").stop()... 

DEMO

+0

這個作品非常完美。謝謝。 – sidewinder 2011-04-11 11:29:59

+0

它也值得看看.hover()函數,因爲它會壓縮你的代碼。 – 2011-04-11 11:31:37

+0

這實際上很聰明,但它確實需要一點盯着:) +1 – karim79 2011-04-11 11:34:59

2

嘗試使用.hasClass()

if($(this).parent().hasClass("active")) { 
    $(this).stop().animate({'color': '#a5acb2'}, 'slow'); 
} 

如果你的列表中的項目只能被分配一個類,你可以這樣做:

// class not equals 'active' 
$(this).parent("[class!='active']"); 

否則,這應該工作:

// class contains 'active' 
$(this).parent("[class*='active']"); 
+0

第一個將無法正常工作,但第二個是好的:) *編輯:+1第二(現在只有)解決方案。* – 2011-04-11 11:29:32

+0

是的,我意識到:) – karim79 2011-04-11 11:30:31

+0

@Felix Kling - 兩種可能性只是爲了好玩:) – karim79 2011-04-11 11:42:15

0
$(".top_nav li a").hover( function() { 

    $(this).stop().animate({'color': '#ffffff'}, 'slow'); 

    }, 

    function() { 

    $(this).parent().not(".active").stop().animate({'color': '#a5acb2'}, 'slow'); 

    }); 
+0

這是行不通的。雖然使用'懸停'是一種更好的方法,但這不是問題。問題在於爲動畫選擇正確的元素。 – 2011-04-11 11:39:00