1:代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 元素样式初始化: 学到盒模型再详细介绍 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
a {
/* color: rgba(255, 255, 255, 0.7); */
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>
</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>
<li><a href="">显卡</a>
</li>
</ul>
</body>
<script>
const navs =document.querySelectorAll("#nav > li");
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";
}
}
function closeSubMenu(ev){
if (ev.target.nextElementSibling !==null) {
ev.target.nextElementSibling.style.display = "none";
}
}
function closeSubMenu(ev) {
if (ev.target.nodeName === "A" && ev.target.nextElementSibling !== null) {
ev.target.nextElementSibling.style.display = "none";
}
}
</script>
</html>
2:效果