jQuery menu on hover open submenu

ⅰ亾dé卋堺 提交于 2020-08-23 08:28:11

问题


I am trying to design something like the followingL

<ul class="top">
  <li><a href="#">Menu1</a></li>
  <li>
    <a href="#">Menu2</a>
    <ul class="sub">
      <li><a href="#">SubMenu1</a></li>
      <li>
        <a href="#">SubMenu2</a>
        <ul class="subsub">
          <li><a href="#">SubSubMenu1</a></li>
          <li><a href="#">SubSubMenu2</a></li>
        </ul>
      </li>
      <li><a href="#">SubMenu3</a></li>
    </ul>
  </li>
  <li><a href="#">Menu3</a></li>
</ul>

And my idea is that if the Node has subNodes, then the submenu will open. So in this instance, if the user hovers on Menu2, the SubMenu1, SubMenu2, and SubMenu3 will appear, and if the user hovers on SubMenu2, SubSubMenu1, SubSubMenu2 will appear.

I have the following jQuery at the moment:

$(document).ready(function () {
  $("ul.top li").hover(function () { //When trigger is hovered...
    if ($("ul.top li").hasClass("sub")) {
      $(this).parent().find("ul.sub").slideDown('fast').show();
      $(this).parent().hover(function () {}, function () {
        $(this).parent().find("ul.sub").slideUp('slow');
      });
    }
  });
});

However when I hover on Menu1, the submenus for Menu 2 are still opening.

Any help will be very much appreciated!


回答1:


You have a couple of issues that need to be resolved. First, you should provide two arguments to the hover() function, the first is a function for onmouseenter, the other is for onmouseleave.

Next, just tag all sub menus with the same class, e.g., sub. This will make writing you selectors much easier.

Use the children() function to only apply the animation to direct children of the item that the user is hovering over.

$(document).ready(function () {
    $("ul.top li").hover(function () { //When trigger is hovered...
        $(this).children("ul.sub").slideDown('fast');
    }, function () {
        $(this).children("ul.sub").slideUp('slow');
    });
});

Working Example



来源:https://stackoverflow.com/questions/17746004/jquery-menu-on-hover-open-submenu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!