Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:下拉菜单 , 有多种实现的dom结构, 目前 咱们教的是最经典的, 当然并不是最简洁的, 以后学到flex会发现还可以大量简化代码的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>下拉菜单</title>
<style>
/* 元素样式初始化 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
a {
color: #bbb;
text-decoration: none;
}
#nav {
background-color: black;
height: 50px;
line-height: 50px;
}
li {
list-style: none;
margin: 0 10px;
float: left;
}
#nav > li > a:hover {
color: white;
}
#nav > li {
position: relative;
}
#nav > li > ul {
position: absolute;
top: 50px;
width: 180px;
border: 1px solid #aaa;
border-top: none;
}
#nav > li > ul > li a {
display: inline-block;
height: 50px;
color: #444;
}
ul.sub li:hover {
background-color: #eee;
}
/* 初始化时不要显示 */
#nav > li > ul {
display: none;
}
</style>
</head>
<body>
<ul id="nav">
<li><a href="">首页</a></li>
<li>
<a href="">公司产品</a>
<ul>
<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="">寻找帮助</a></li>
<li>
<a href="">公司地点</a>
<ul>
<li><a href="">总部</a></li>
<li><a href="">分部</a></li>
<li><a href="">事业部</a></li>
<li><a href="">海外</a></li>
</ul>
</li>
</ul>
</body>
<script>
// 获取所有的主导航
const navs = document.querySelectorAll("#nav>li");
//console.log(navs);
navs.forEach(function (nav) {
//鼠标移入时,显示子菜单
nav.addEventListener("mouseover", showSubMenu);
//鼠标移出时,关掉子菜单
nav.addEventListener("mouseout", closeSubMenu);
});
function showSubMenu(ev) {
//判断当前这个导航有没有子菜单
if (ev.target.nextElementSibling !== null) {
ev.target.nextElementSibling.style.display = "block";
}
}
//判断有没有元素标签A
function closeSubMenu(ev) {
if (ev.target.nodeName === "A" && ev.target.nextElementSibling !== null) {
ev.target.nextElementSibling.style.display = "none";
}
}
</script>
</html>