代码演示:
<!DOCTYPE html>
<html lang="zh">
<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;
}
html,
body {
height: 100%;
width: 100%;
}
html {
font-size: 10px;
}
.bg {
width: 100%;
height: 5rem;
background-color: oldlace;
display: flex;
justify-content: center;
align-items: center;
}
.nav {
width: 60rem;
height: 5rem;
display: flex;
justify-content: start;
list-style: none;
/* background-color: red; */
align-items: center;
position: relative;
}
.nav>.item {
text-align: center;
padding: 0 5rem;
/* height: 5rem; */
list-style: none;
font-size: 15px;
font-weight: 500;
cursor: pointer;
}
.children {
position: absolute;
background-color: #5c9eb8;
height: 160px;
width: 80px;
list-style: none;
margin-top: 14px;
}
.children li {
margin-top: 20px;
}
</style>
</head>
<body>
<div class="bg">
<ul class="nav">
<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);
for (let i = 0; i < _lis.length; i++) {
// console.log(_lis[isSecureContext],"---");
// _lis[i].onmouseennter = function () {
// // console.log("用户点击了第" + (i + 1) + "个菜单");
// let child = _lis[i].getElementsByClassName("children")
// // console.log(_children);
// if (child.length > 0) {
// child[0].style.display = "block"
// }
// }
// _lis[i].onmouseleave = function () {
// let child = _lis[i].getElementsByClassName("children")
// if (child.length > 0) {
// child[0].style.display = "none"
// }
// }
_lis[i].onclick = function () {
let _children = _lis[i].getElementsByClassName("children")
// console.log(_children);
if (_children.length > 0) {
let c = _children[0]
if (c.style.display == "none") {
c.style.display = "block"
} else {
c.style.display = "none"
}
}
}
}
</script>
</body>
</html>
图片展示:
屏幕截图 2025-03-26 180627.png
收获:
1.学会了如何对二级标签添加样式
2.学会了如何展示菜单和隐藏菜单