<!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;
}
html,
body {
width: 100%;
height: 100%;
}
html {
font-size: 10px;
}
.bg {
width: 100%;
height: 5rem;
display: flex;
justify-content: center;
background-color: antiquewhite;
}
.nav {
font-size: large;
display: flex;
justify-content: center;
list-style: none;
line-height: 5rem;
gap: 5rem;
background-color: bisque;
}
.nav li {
height: 5rem;
padding: 0 5rem;
position: relative;
}
.nav li ul.children {
display: none;
position: absolute;
background-color: rgba(255, 228, 196, 0.767);
text-align: center;
list-style: none;
width: 100%;
left: 0;
}
.nav li ul.children li {
padding: 0;
line-height: 3rem;
}
.nav li:hover ul.children {
display: block;
}
</style>
</head>
<body>
<div class="bg">
<ul class="nav">
<li class="item">主页</li>
<li class="item">文章
<ul class="children">
<li>文章1</li>
<li>文章2</li>
<li>文章3</li>
</ul>
</li>
<li class="item">相册
<ul class="children">
<li>相册1</li>
<li>相册2</li>
<li>相册3</li>
</ul>
</li>
<li class="item">留言
<ul class="children">
<li>留言1</li>
<li>留言2</li>
<li>留言3</li>
</ul>
</li>
</ul>
</div>
<script>
let menu1 = document.getElementsByClassName("item")
console.log(menu1)
for (let i = 0; i < menu1.length; i++) {
menu1[i].onmouseover = function () {
console.log("用户进入了编号为",i,"的菜单")
let child = menu1[i].getElementsByTagName("children")
if (child.length > 0) {
child[0].style.display = "block"}
}
menu1[i].onmouseout = function () {
let child = menu1[i].getElementsByTagName("children")
if (child.length > 0) {
child[0].style.display = "none"
}
}
}
</script>
</body>
</html>