2011-04-11 212 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

相关问题