我正在尝试使用汉堡图标切换 ul 元素的显示,使得当我点击图标时,ul 元素可以显示或隐藏。
这是我的代码:
ul 元素会快速消失并且不能保持可见状态。我想要通过点击汉堡菜单来显示或隐藏 ul 元素。非常感谢您的帮助。
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]> <html class="no-js"> <!--<![endif]-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Fashionation</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<nav>
<a href="#">Brand Name</a>
<ul id="list">
<li><a href="">Home</a></li>
<li><a href="">New Arrivals</a></li>
<li><a href="">Clothes</a></li>
<li><a href="">Sales</a></li>
<li><a href="">Stores</a></li>
<li><a href="">About</a></li>
<li><a href="">Contact</a></li>
</ul>
<a href="" class="menu" id="menu" onclick="displayMenu()"><i class="fa fa-bars fa-2x"></i></a>
</nav>
</header>
<script src="script.js"></script>
</body>
</html>
CSS(层叠样式表)
* {
margin: 0;
padding: 0;
box-sizing: border-box;
list-style-type: none;
text-decoration: none;
}
body {
/* background-color: red; */
}
header {
height: 450px;
/* background-color: orangered; */
}
nav {
height: 50px;
background-color: #262626;
line-height: 50px;
position: relative;
}
nav ul {
/* background-color: orangered; */
margin-top: 10px;
margin-bottom: 10px;
/* display: none; */
}
nav ul li {
padding: 2px;
text-align: center;
}
a {
color: #C70D6C;
}
.menu {
color: #C70D6C;
position: absolute;
top: 6px;
right: 10px;
line-height: 50px;
display: none;
}
@media screen and (max-width: 767.98px) {
.menu {
display: inline-block;
}
}
JavaScript
function displayMenu() {
let list = document.getElementById('list');
if (list.style.display === "none") {
list.style.display = "block";
} else {
list.style.display = "none";
}
}