在前端佈局後臺管理界面中,我們在創建導航菜單的時候,經常會有菜單項內嵌子菜單佈局,點擊菜單項實現子菜單的顯示與影藏。實現結果其實很簡單,控制子菜單列表的 css 樣式:display: block/none
。
style.css文件:
* {
margin: 0;
padding: 0;
}
li{
list-style: none;
}
a{
text-decoration: none;
}
body{
height: 100vh;
display: flex;
flex-flow: column nowrap;
/*控制鼠標雙擊複製文本*/
-ms-user-select: none;
-moz-user-select: none;
user-select: none;
}
header{
display: flex;
height: 70px;
background-color: #464d5f;
align-items: center;
font-size: 1.8rem;
padding-left: 24px;
color: white;
}
main{
flex: 1;
background-color: #ccddcc;
overflow: hidden;
}
main > aside {
display: flex;
flex-flow: column nowrap;
width: 300px;
height: 100%;
padding-top: 10px;
background-color: #4d5669;
}
main > aside > li{
cursor: pointer;
}
main > aside > li strong{
display: block;
padding-left: 24px;
height: 60px;
line-height: 60px;
color: #f2f2f2;
}
main > aside > li > ul {
background-color: #464d5f;
}
/*控制子菜單隱藏*/
.display{
display: none;
}
main > aside > li > ul > li{
padding: 5px 48px ;
color: #f2f2f2;
}
index.html文件:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>商品信息</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<header>後臺界面</header>
<main>
<aside id="menu">
<li>
<strong>主菜單</strong>
<ul class="display">
<li>子菜單</li>
<li>子菜單</li>
</ul>
</li>
<li><strong>產品管理</strong></li>
<li><strong>庫存管理</strong></li>
<li><strong>權限設置</strong></li>
<li><strong>系統設置</strong></li>
</aside>
</main>
<script>
// 控制導航摺疊
let menus = document.querySelectorAll("#menu > li");
let sub = document.querySelector("#menu > li > ul");
menus.forEach(function (menu) {
menu.firstElementChild.addEventListener('click', function (evt) {
// 獲取子菜單元素ul
evt.target.nextElementSibling.classList.toggle('display');
})
}, false);
</script>
</body>
</html>
代碼效果:
THE END!