How do I target a top-level link in a layered unordered list?

I have a multi-level navigator created as an unordered list that looks like this:

<ul id="nav-menu"> ... <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 upper level is designed so that when the background freezes. My problem is that this background disappears when the cursor moves to the submenu. I am trying to use jquery to add a class to the top level anchor when its submenu freezes. Any suggestions?

An example of suitable 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; } 
+4
source share
2 answers

In order for the main <li> to preserve the style when hovering secondary links, you need to apply the style :hover to <li> , and not to <a> inside 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 */} 

Remember to neutralize the #nav-menu li:hover styles for secondary <li> elements. You can use #nav-menu > li:hover , I think, but browser support is not so strong.

+3
source

@Tyler, try using Mouseenter, Mouseleave instead of mouseover and mouseout, which will fix your problem.

http://api.jquery.com/mouseenter/

+2
source

Source: https://habr.com/ru/post/1346402/


All Articles