javascript - 如何使用 javascript 使导航栏整齐地打开和关闭?
问题描述
我想用以下功能制作一个好的导航栏,但我似乎无法在 javascript 中弄清楚。
我希望它具有以下功能:
- 单击汉堡图标时会打开菜单
- 再次单击汉堡图标时菜单关闭
- 如果单击菜单中的链接,菜单也会关闭
- 如果单击菜单外的任何位置,菜单也会关闭
我已经为我的 css 菜单类添加了一个(.active,它可以切换是否显示菜单。)现在我最初做了一个 onclick 功能,但这不仅不是一个好习惯,它也没有给出我想要的用户体验。这是因为菜单出现或消失的唯一方法是按下汉堡菜单。
这是一些基本的 html 和 css,与我正在使用的类似:
这是一个 JSFiddle:https ://jsfiddle.net/L0vr8j59/
(注意:汉堡图标仅通过媒体查询出现在屏幕宽度 800px 或以下)
HTML:
<nav class="navbar">
<div class="nav-list">
<ul id="menu">
<li><a href="#link1">Link 1</a></li>
<li><a href="#link2">Link 2</a></li>
<li><a href="#link3">Link 3</a></li>
<li><a href="#link4">Link 4</a></li>
</ul>
<div id="hamburger" class="hamburgermenu">
<span></span>
<span></span>
<span></span>
</div>
</div>
</nav>
CSS:
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
html{
scroll-behavior: smooth;
}
li{
font-size: 2.75rem;
}
li a:hover{
text-decoration: overline;
}
.hamburgermenu{
display: none;
flex-direction: column;
align-items: center;
justify-content: center;
}
.hamburgermenu span{
display: flex;
justify-content: center;
align-items: center;
height: 4px;
width: 40px;
margin: 4px;
background: black;
}
ul{
display: flex;
justify-content: space-around;
list-style-type: none;
}
ul a{
text-decoration: none;
font-size: 1.5rem;
color: black;
}
.navbar{
overflow: hidden;
position: fixed;
top: 0;
width: 100%;
}
.navbar::before{
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
box-shadow: inset 0 0 2000px rgba(255, 255, 255, .5);
filter: blur(5px);
z-index: -10;
color: white;
}
.navbar.active{
background-color: black;
color: white;
z-index: 20;
}
.navbar.active::before{
box-shadow: none;
}
.navbar.active ul a {
color: white;
}
.navbar.active .hamburgermenu span{
background-color: white;
}
.nav-list{
display: block;
padding-left: 50%;
line-height: 5rem;
padding-bottom: 5px;
}
@media screen and (max-width: 800px) {
.nav-list{
display: flex;
flex-direction: column-reverse;
}
#menu{
display: none;
opacity: 0;
}
#menu.active{
position: relative;
display: flex;
top: 5px;
background-color: rgb(61, 60, 60);
flex-direction: column;
align-items: center;
opacity: 1;
transition: 5ms ease-in;
}
ul a{
color: white;
}
.hamburgermenu{
display: flex;
visibility: visible;
margin-top: 1.5rem;
margin-bottom: 1.5rem;
align-items: flex-end;
padding-right: 2rem;
}
如果需要,我还可以提供任何其他信息。
提前致谢。:D