[英]Hiding css dropdown menu on hover
In the navigation bar, on click of "Home 3" menu, a dropdown menu appears through jQuery. 在导航栏中,单击“主页3”菜单,通过jQuery出现一个下拉菜单。 I want to hide this menu when I hover on other links of the menu for which I have included style as below: 当我将鼠标悬停在包含以下样式的菜单的其他链接上时,我想隐藏此菜单:
.nav-ul .menu-item:hover ul{
display:none;
}
Here is the fiddle: http://jsfiddle.net/Tw44R/1/ 这是小提琴: http : //jsfiddle.net/Tw44R/1/
The selector .nav-ul .menu-item:hover ul
will only target the <ul>
inside the .menu-item
item being hovered. 选择器.nav-ul .menu-item:hover ul
将仅针对要悬停的.menu-item
项目内的<ul>
。
You can't traverse up the DOM
using CSS as of now. 到目前为止,您无法使用CSS遍历DOM
。
Add the following script: 添加以下脚本:
$('.menu-item').hover(function(){
$(this).siblings().find('ul').hide();
});
Update: 更新:
If you want to hide the dropdown when the mouse moves away, you can use the second callback of hover, as given below: 如果要在鼠标移开时隐藏下拉菜单,可以使用悬停的第二个回调,如下所示:
$('.menu-item').hover(function () {
$(this).siblings().find('ul').hide();
},
function () {
$(this).find('ul').hide()
});
Side note: For anyone down voting seeing Yury Tarabanko 's comment, it's not a reliable solution for the task at hand ( it doesn't work if the submenu is before the hovered item ). 旁注:对于任何投下Yury Tarabanko的评论的人,这都不是解决当前任务的可靠解决方案 ( 如果子菜单位于悬停的项目之前,则该方法不起作用 )。
Try with jQuery's mouseenter: 尝试使用jQuery的mouseenter:
$(function () {
$(".nav-header .nav-ul .menu-item .menu-item-link").click(function (link) {
if (link.currentTarget.text === 'Home 3') {
$(this).next("ul").css('display', 'block');
}
link.stopPropagation();
}).mouseenter(function () {
$(".nav-header .nav-ul .menu-item ul:visible").css('display', 'none');
});
});
You can use this approach: 您可以使用这种方法:
$(".nav-header .nav-ul .menu-item").hover(function (){
$(".menu-item").each(function(){
if($(this).find("ul").css("display") == "block")
$(this).find("ul").css("display","none");
});
})
Check out this JSFiddle .. 看看这个JSFiddle ..
EDIT: I shouldn't used .menu-item-link, just edited the JSFiddle too. 编辑:我不应该使用.menu-item-link,也只需编辑JSFiddle。 Everything works fine.. Thank you for pointing out my mistake.. 一切正常。.感谢您指出我的错误..
This solution will open the sub-menu with a click and close the sub-menu when you move away from either the header or the sub-menu. 当您离开标题或子菜单时,此解决方案将通过单击打开子菜单,然后关闭子菜单。
I gave each header item an id 我给每个标头项目指定了一个ID
<li class="menu-item" id="3">
Then: 然后:
$(function(){
$("#3").click(function(){
$(".nav-ul .menu-item ul").css('display', 'block');
});
$("#3").mouseleave(function(){
$(".nav-ul .menu-item ul").css('display', 'none');
});
});
Check it out: 看看这个:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.