页面展示

代码演示
<!DOCTYPE html>
<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:bisque;
display:flex;
justify-content:center;
}
.page-header{
width:1200px;
height:100%;/* background-color: orange; */
display:flex;
list-style: none;
}
.page-header > .item{
padding:10px 50px;
font-size:18px;
text-align:center;
cursor: pointer;
position: relative;
}
.page-header > .item:hover{
background-color: #f2f2f1;
color:#333;
font-weight:500;
}
.children{
display:none;
position:absolute;
top: 50px;
left: 0;
list-style:none;
padding: 10px 20px;
background-color:aquamarine;
}
.children > li{
line-height: 50px;
}
.children > li:hover{
background-color: #f2f2f1;
color:#333;
}
</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>
<!-- js代码写在网页的最后面 -->
<script>
// 获取所有的一级菜单;<li class="item"></li>
let _lis = document.getElementsByClassName("item")
console.log(_lis)
// 循环依次添加单击事件
for(let i = 0; i < _lis.length; i++) {
// 依次添加单击事件 -> 鼠标进入事件
_lis[i].onmouseenter = function() {
// 获取当前点击标签内部的<ul class="children"></ul>
let _children = _lis[i].getElementsByClassName("children")
// 判断是否有子标签
if(_children.length > 0) {
// 如果有,获取子标签
let c = _children[0]
// 判断显示子标签
c.style.display = "block"
}
}
// 依次添加一个鼠标离开事件
_lis[i].onmouseleave = function(){
// 获取当前点击标签内部的<ul class="children"></ul>
let _children = _lis[i].getElementsByClassName("children")
// 判断是否有子标签
if(_children.length > 0) {
// 如果有,获取子标签
let c = _children[0]
// 判断隐藏子标签
c.style.display = "none"
}
}
}
</script>
</body>
</html>