我如何让这个 ul li 下拉菜单在 jquery 或 javascript 悬停时显示?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8363973/
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
How do I get this ul li dropdown menu to show on hover with jquery or javascript?
提问by Rolando
I have the following CSS:
我有以下 CSS:
<ul id="nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle">Dropdown Appear 1</a>
<ul class="dropdown-menu">
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
</ul>
</li>
<li><a href="#contact">Somelink</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">Dropdown Appear 2</a>
<ul class="dropdown-menu">
<li><a href="#">Another Item 1</a></li>
<li><a href="#">Another Item 2</a></li>
</ul>
</li>
</ul>
Currently in CSS the dropdown-menu has a "display: none" property set. I want to make it so that without having to assign ID's to any of my DOM elements, a user can hover over or click "Dropdown Appear 1" or "Dropdown Appear 2" and show their respective dropdown menus. How do I accomplish this? (Would be nice if there was a slide down transition.)
目前在 CSS 中,下拉菜单有一个“display: none”属性集。我想让它不必为我的任何 DOM 元素分配 ID,用户可以将鼠标悬停在或单击“Dropdown Appear 1”或“Dropdown Appear 2”并显示各自的下拉菜单。我该如何实现?(如果有滑下过渡就太好了。)
回答by David says reinstate Monica
The easiest way would be to apply the hover
to the li
, that way when the user hovers over the sub-menu they don't trigger the mouseout event from leaving the a
element:
最简单的方法是应用hover
的li
,这样当在子菜单中的用户悬停他们不离开触发mouseout事件a
元素:
$('li.dropdown').hover(
function(){
$(this).find('ul').slideDown();
},
function(){
$(this).find('ul').slideUp();
});
References:
参考:
回答by cqde
Is there a reason you want to do this specifically with JS? Effects, animations, etc?
你有什么理由专门用 JS 来做这件事吗?效果,动画等?
Not sure if you are just trying to display the sub menu on hover because you can do this purely with CSS (and without adding unique ID's to each nested unordered list). You would set your nested list's display to "none" and on hover over the parent list's "li" element, you could change the display to "block".
不确定您是否只是尝试在悬停时显示子菜单,因为您可以完全使用 CSS 来完成此操作(并且无需向每个嵌套的无序列表添加唯一 ID)。您可以将嵌套列表的显示设置为“无”,并将鼠标悬停在父列表的“li”元素上,您可以将显示更改为“块”。
#nav li.dropdown ul { display: none; }
#nav li.dropdown:hover ul { display: block; }
Again, not sure if you wanted to use JS specifically. But, at least with this route, the user will still see the dropdown in case he/she has JS disabled (which we hope not!).
同样,不确定您是否想专门使用 JS。但是,至少在这条路线上,用户仍然会看到下拉菜单,以防他/她禁用了 JS(我们希望不是!)。
回答by AR.
$(document).ready(function(){
$('.dropdown').each(function(){
$(this).find('ul').hide();
});
$('.dropdown').hover(function(){
$(this).find('ul').slideDown();
},
function(){
$(this).find('ul').slideUp();
});
});