3

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!

4

1 回答 1

11

你有几个问题需要解决。首先,您应该为hover()函数提供两个参数,第一个是 onmouseenter 的函数,另一个是 onmouseleave 的函数。

接下来,只需用相同的类标记所有子菜单,例如sub. 这将使编写选择器更加容易。

使用children()函数仅将动画应用于用户悬停的项目的直接子项。

$(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');
    });
});

工作示例

于 2013-07-19T12:34:31.180 回答