简体   繁体   中英

jQuery drop-down navigation using unordered lists

I'm trying to make a navigation dropdown with jQuery that looks like this:

<ul id="home" >
    <li class="navtab"><a href="#">TABANME</a></li>
    <li class="homesub"><a href="#">Some link</a></li>
    <li class="homesub"><a href="#">Some link</a></li>
    <li class="homesub"><a href="#">Some link</a></li>
</ul>

The <li> .navtab is visible at all times - the submenu items start out hidden. I've attached the .hover() to the <ul> element (#home), but when the cursor enters the submenu <li> elements, the mouseout for #home fires, and the submenu items hide.

I know this has to do with event bubbling and mouseover/mouseout, but I can't figure out the logic of how to keep the menu open while the cursor is over the entire <ul> . The jQuery I currently have is:

    $('#thome').hover(
        function(){
           tabShowSubnav($(this).attr('id'))
        },
        function(){
           tabHideSubnav($(this).attr('id'))
        });

function tabShowSubnav(menu){

var tb = '#' + menu;
var sb = '.' + menu.slice(1) + 'sub';

$(tb).css('height','239px');
$(sb).show();
}

Any suggestions?

Do yourself a huge favour and change how you structure your menu markup to:

<ul id="home" >
  <li class="navtab">
    <a href="#">TABANME</a>
    <ul class="submenu">
      <li><a href="#">Some link</a></li>
      <li><a href="#">Some link</a></li>
      <li><a href="#">Some link</a></li>
    </ul>
  </li>
</ul>

And put the hover event on li.navtab to make the submenu visible. You'll find this much easier to do. For example, the CSS:

ul.submenu { display: none; }

with:

$(function() {
  $("li.navtab").hover(function() {
    $(this).children("ul.submenu").show();
  }, function() {
    $(this).children("ul.submenu").hide();
  });
});

and you're most of the way there.

That all being said, I'd highly suggest using an existing jQuery menu plugin. There are lots of these about. I've had relatively good experience with superfish . There's little point reinventing this particular wheel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM