效果展示
屏幕截图 2025-03-28 195609.png
代码实现
<html lang="zh">
<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;
}
html,
body {
width: 100%;
height: 100%;
}
body {
font-size: 62.5%;
}
.nav {
width: 100%;
height: 50px;
background-color: #eaa818;
display: flex;
justify-content: center;
}
.page-header {
width: 1200px;
height: 100%;
/* background-color: #31eadb; */
display: flex;
list-style: none;
}
.page-header .item {
padding: 10px 50px;
cursor: pointer;
font-size: 18px;
text-align: center;
position: relative;
}
.page-header .item:hover {
background-color: hsl(0, 2%, 79%);
color: hwb(0 3% 97%);
font-weight: 500;
}
.children {
list-style: none;
padding: 10px 20px;
background-color: #e28354;
position: absolute;
top: 50px;
left: 0;
display: none;
}
.children li {
line-height: 50px;
}
.children li:hover {
background-color: #dedcdc;
color: #070707;
}
</style>
</head>
<body>
<div class="nav">
<ul class="page-header">
<li class="item">首页</li>
<li class="item">文章
<ul class="children">
<li>发表文章</li>
<li>我的文章</li>
<li>关注的文章</li>
<li>喜欢的文章</li>
</ul>
</li>
<li class="item">相册
<ul class="children">
<li>我的相册</li>
<li>上传照片</li>
</ul>
</li>
<li class="item">消息
<ul class="children">
<li>我的私信</li>
<li>我的留言</li>
</ul>
</li>
</ul>
</div>
<script>
// 获取所有的一级菜单
let _lis = document.getElementsByClassName("item")
console.log(_lis)
// 分装函数
function toggleMenu( child,is_show) {
let _children = child.getElementsByClassName("children")
if (_children.length > 0) {
let c = _children[0]
c.style.display = is_show
}
}
// 循环依次添加单击事件
for (let i = 0; i < _lis.length; i++) {
_lis[i].onmouseenter = function () {
toggleMenu(_lis[i],"block")}
// let _children = _lis[i].getElementsByClassName("children") //
// if (_children.length > 0) {
// let c = _children[0]
// c.style.display = "block"
// }
// }
_lis[i].onmouseleave = function () {
toggleMenu(_lis[i],"none")}
// let _children = _lis[i].getElementsByClassName("children")
// if (_children.length > 0) {
// let c = _children[0]
// c.style.display = "none"
// }
}
</script>
</body>
</html>