How to target a top-level link in a multi-level unordered list?
I have a multi-level nav styled as an unordered list that looks like this:
<ul id="nav-menu">
...
开发者_Go百科 <li id="menu-item-1">
<a href="#">Category</a>
<ul class="sub-menu">
<li id="menu-item-2">
<a href="#">Sub-Category</a>
</li>
</ul>
</li>
...
</ul>
The top level is styled so that there is a background when hovered. My problem is that this background disappears when the cursor moves to the sub-menu. I'm trying to use jquery to add a class to the top-level anchor when its sub-menu is hovered. Any suggestions?
Sample of pertinent CSS:
#menu-nav li a { /* no background-set */ }
#menu-nav li a:hover { background: #fff; }
.sub-menu li a { background: #ccc; }
.sub-menu li a:hover { background: #999; }
For the primary <li>
to retain styling while hovering secondary links, you'll need to apply your :hover
style to the <li>
rather than the <a>
within it.
JS
$("#nav-menu > li").hover(
function(){ $(this).addClass("hover"); },
function(){ $(this).removeClass("hover"); }
)
CSS
#nav-menu li:hover, #nav-menu li.hover {/* styles here */}
Don't forget to neutralise #nav-menu li:hover
styles on the secondary <li>
elements. You could use #nav-menu > li:hover
I guess but the browser support isn't as strong.
@Tyler , try to use Mouseenter , Mouseleave instead of mouseover and mouseout , that will fix your problem
http://api.jquery.com/mouseenter/
精彩评论