我正在创建一个水平下拉导航,我希望当用户将鼠标悬停在父li元素上时会显示下拉菜单。一切都运行正常,但即使用户没有悬停在li元素上,我也会出现子菜单出现问题。
具体来说,用户第一次访问菜单时效果很好,但在随后的鼠标移动中,即使用户没有悬停在该li元素上,也会出现最后一个li元素的子菜单,或者任何li元件。它就像用户进入标题区域一样。这是代码和jsfiddle:
HTML:
<div id = "header">
<nav id = "main-nav-container">
<ul id = "main-nav-menu">
<li class = "main-nav-item">
<a href = "#" class = "main-nav-link">Item 1</a>
</li>
<li class = "main-nav-item">
<a href = "#" class = "main-nav-link">Item 2</a>
</li>
<li class = "main-nav-item has-sub-menu">
<a href = "#" class = "main-nav-link">Item 3</a>
<ul class = "sub-menu">
<li class = "sub-menu-item">
<a href = "#" class = "sub-menu-link">Sub 1</a>
</li>
<li class = "sub-menu-item">
<a href = "#" class = "sub-menu-link">Sub 2</a>
</li>
<li class = "sub-menu-item">
<a href = "#" class = "sub-menu-link">Sub 3</a>
</li>
</ul>
</li>
<li class = "main-nav-item has-sub-menu">
<a href = "#" class = "main-nav-link">Item 4</a>
<ul class = "sub-menu">
<li class = "sub-menu-item">
<a href = "sub-menu-link">Sub 1</a>
</li>
<li class = "sub-menu-item">
<a href = "sub-menu-link">Sub 2</a>
</li>
<li class = "sub-menu-item">
<a href = "sub-menu-link">Sub 3</a>
</li>
<li class = "sub-menu-item">
<a href = "sub-menu-link">Sub 4</a>
</li>
</ul>
</li>
</ul>
</nav>
</div>
CSS:
body {
background-color:#fff;
font-family: "Open Sans", sans-serif;
}
a {
color:#fff;
text-decoration:none;
}
ul {
list-style:none;
}
.clear:after {
content:".";
clear:both;
height:0;
visibility:hidden;
}
#header {
width:100%;
height:65px;
background-color:#c11728;
transition:height linear .2s;
}
nav {
text-align:right;
}
#main-nav-menu {
display:inline-block;
}
.main-nav-item {
display:inline-block;
position:relative;
white-space:nowrap;
padding:20px;
}
.sub-menu {
display:inline-block;
opacity:0;
position:absolute;
margin-top:30px;
transition:opacity ease .2s;
left:0;
}
.sub-menu-item {
display:inline;
padding:5px 20px;
}
.show-menu {
opacity:1;
z-index:10;
}
JQuery的:
$("#main-nav-menu .main-nav-item:not(:last-child) .sub-menu").each(function() {
var newPos = $(this).width() - 90;
$(this).css("transform", "translateX(-" + (newPos/2) + "px)");
});
$("#main-nav-menu .main-nav-item:last-child .sub-menu").each(function() {
var newPos = $(this).width() - 90;
$(this).css("transform", "translateX(-" + (newPos) + "px)");
});
$(".has-sub-menu").mouseover(function(e) {
e.stopPropagation;
$(this).children(".sub-menu").addClass("show-menu");
var addHeight = $(this).children(".sub-menu").height();
$("#header").css("height", ((65 + addHeight) + "px"));
}).mouseout(function(e) {
e.stopPropagation;
var newPos = $(this).children(".sub-menu").width() - 90;
$(this).children(".sub-menu").removeClass("show-menu");
$("#header").css("height", (65 + "px"));
});
的jsfiddle:
我想我的问题是为什么。为什么会这样?为什么将show-menu类添加到子菜单的mouseover事件是否会触发,即使用户没有将鼠标悬停在附加到它上面的li元素上?我没看到什么?谢谢!