作業(yè)分析
本次要求編寫一個(gè)下拉菜單效果,如下圖

image.png

image.png
代碼實(shí)現(xiàn)
<!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%;
}
body {
font-size: 62.5%
}
.nav {
width: 100%;
height: 50px;
background-color: bisque;
display: flex;
justify-content: center;
}
.page-header {
width: 1200px;
height: 100%;
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>發(fā)表文章</li>
<li>我的文章</li>
<li>關(guān)注的文章</li>
<li>喜歡的文章</li>
</ul>
</li>
<li class="item">相冊(cè)
<ul class="children">
<li>我的相冊(cè)</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")
}
_lis[i].onmouseleave = function () {
toggleMenu(_lis[i], "none")
}
}
</script>
</body>
</html>