javascript 悬停打开子菜单上的jQuery菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17746004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery menu on hover open submenu
提问by Johann
I am trying to design something like the followingL
我正在尝试设计类似以下L的东西
<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.
我的想法是,如果节点有子节点,则子菜单将打开。所以在这个例子中,如果用户悬停在Menu2上,就会出现SubMenu1、SubMenu2和SubMenu3,如果用户悬停在SubMenu2上,就会出现SubSubMenu1、SubSubMenu2。
I have the following jQuery at the moment:
我目前有以下 jQuery:
$(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.
但是,当我将鼠标悬停在 Menu1 上时,Menu 2 的子菜单仍在打开。
Any help will be very much appreciated!
任何帮助将不胜感激!
回答by cfs
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.
您有几个问题需要解决。首先,您应该为hover()函数提供两个参数,第一个是onmouseenter 的函数,另一个是onmouseleave 的函数。
Next, just tag all sub menus with the same class, e.g., sub
. This will make writing you selectors much easier.
接下来,只需用相同的类标记所有子菜单,例如,sub
。这将使您更轻松地编写选择器。
Use the children()function to only apply the animation to direct children of the item that the user is hovering over.
使用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');
});
});