Selecting an element whose parent element does not have a particular class
Assuming, I have the following 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>
When the mouse leaves the LI element, it is suppose change the color of the font back to grey except for the A element whose parent LI has a class value of 'active'.
Below is the JQuery code I am trying: (The 'mouseleave' function is not working)
$(".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');
});
$(this).parent()
selects the li
element and all other functions apply to this one instead to the a
element.
You can do:
$(this).not(".active > a").stop()...
DEMO
Try using .hasClass()
:
if($(this).parent().hasClass("active")) {
$(this).stop().animate({'color': '#a5acb2'}, 'slow');
}
If your list items can only be assigned the one class, you can do this:
// class not equals 'active'
$(this).parent("[class!='active']");
Otherwise, this should work:
// class contains 'active'
$(this).parent("[class*='active']");
$(".top_nav li a").hover( function () {
$(this).stop().animate({'color': '#ffffff'}, 'slow');
},
function () {
$(this).parent().not(".active").stop().animate({'color': '#a5acb2'}, 'slow');
});
精彩评论