效果
文档结构
<div class="nav">
<ul>
<li class="first"><a href="">菜单1</a></li>
<li><a href="">菜单2</a></li>
<li>
<a href="">菜单3</a>
<ul class="subMenu">
<li><a href="">子菜单</a></li>
<li><a href="">子菜单</a></li>
<li><a href="">子菜单</a></li>
<li><a href="">子菜单</a></li>
<li><a href="">子菜单</a></li>
<li><a href="">子菜单</a></li>
</ul>
</li>
<li><a href="">菜单4</a></li>
<li>
<a href="">菜单5</a>
<ul class="subMenu">
<li><a href="">子菜单</a></li>
<li><a href="">子菜单</a></li>
<li><a href="">子菜单</a></li>
<li><a href="">子菜单</a></li>
<li><a href="">子菜单</a></li>
<li><a href="">子菜单</a></li>
<li><a href="">子菜单</a></li>
<li><a href="">子菜单</a></li>
</ul>
</li>
</ul>
</div>
js代码
<script>
//获取导航菜单
const navs = document.querySelectorAll(".nav>ul>li");
//获取子菜单
const subs = document.querySelectorAll(".subMenu");
// 为导航菜单添加监听事件
navs.forEach(function (li) {
li.addEventListener("mouseover", showSubMenu);
li.addEventListener("mouseout", closeSubMenu);
});
// 为子菜单添加监听事件,解决主导航切换到子菜单,子菜单消失问题
subs.forEach(function (ul) {
ul.addEventListener("mouseover", function (e) {
this.style.display = "block";
});
ul.addEventListener("mouseout", function (e) {
this.style.display = "none";
});
});
function showSubMenu(e) {
// 判断当前导航是否有子菜单
if (e.target.nextElementSibling != null) {
e.target.nextElementSibling.style.display = "block";
}
}
function closeSubMenu(e) {
// console.log(e.target);
// 判断当前导航是否有子菜单并且当前触发事件的为菜单标签
if (e.target.nextElementSibling != null && e.target.nodeName == "A") {
e.target.nextElementSibling.style.display = "none";
}
}
</script>
样式表
<style>
* {
padding: 0;
margin: 0;
}
a {
text-decoration: none;
}
li {
list-style: none;
}
.nav > ul > li {
float: left;
height: 60px;
line-height: 60px;
color: #fff;
position: relative;
}
.nav > ul > li > a {
color: #fff;
padding: 0 30px;
height: 56px;
display: inline-block;
}
.nav > ul > li > a:hover {
border-bottom: 4px solid rgb(13, 151, 0);
}
.subMenu {
display: none;
color: #333;
position: absolute;
width: 200px;
border: 1px solid #ddd;
text-align: center;
top: 60px;
left: -50px;
background: #f4f4f4;
}
.subMenu li {
float: left;
}
.subMenu a {
float: left;
padding: 0 20px;
width: 60px;
color: #333;
}
.subMenu a:hover {
background: #ddd;
}
.nav {
height: 60px;
background: #000;
width: 100%;
padding-left: 150px;
}
.first {
background: #333;
}
</style>