1 回答
TA贡献1911条经验 获得超7个赞
使用Element.querySelector()和Element.querySelectorAll()
由于您有一个链接集合,因此可以对它们进行迭代,.forEach()以便为每个锚点分配一个点击侦听器。
const
burger = document.querySelector("#burger"),
nav = document.querySelector("#main-nav"), // Use ID, if you already use one.
a = document.querySelectorAll(".nav-link"); // PS: Use the right selectors!
burger.addEventListener("click", function(e) {
this.classList.toggle("is-open");
nav.classList.toggle("is-open");
});
a.forEach(el => el.addEventListener("click", function(e) {
burger.classList.toggle("is-open");
nav.classList.toggle("is-open");
}));
body {
background: #000;
}
.main-nav {
position: absolute;
top: 0;
right: 0;
left: -18px;
text-align: center;
background: #fff;
opacity: 0;
z-index: -1;
visibility: hidden;
-webkit-transition: .375s;
transition: .375s;
height: 100vh;
margin: 0 !important;
}
.main-nav.is-open {
opacity: 1;
z-index: 100;
visibility: visible;
}
.main-nav::before {
content: '';
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: -15px;
background: #000;
transform-origin: 0 0;
transform: skew(-14deg) translateX(-120%);
transition: all .275s .1s;
}
.main-nav.is-open::before {
transform: skew(-14deg) translateX(0);
}
.main-nav ul {
display: inline-flex;
flex-direction: column;
height: 60%;
align-items: flex-end;
justify-content: center;
transform: translateX(-18%) skew(-16deg);
}
.main-nav li {
display: block;
margin: .5rem 0;
text-align: right;
transform: skew(16deg);
}
.main-nav a {
opacity: 0;
transform: translateY(-10px);
}
.main-nav.is-open a {
opacity: 1;
transform: translateY(0);
}
.open-main-nav {
position: absolute;
top: 15px;
padding-top: 20px;
z-index: 1000;
background: none;
border: 0;
cursor: pointer;
}
.open-main-nav:focus {
outline: none;
}
.burger {
position: relative;
display: block;
width: 28px;
height: 4px;
margin: 0 auto;
background: #fff;
transform: skew(5deg);
transition: all .275s;
}
.burger:after,
.burger:before {
content: '';
display: block;
height: 100%;
background: #fff;
transition: all .275s;
}
.burger:after {
transform: translateY(-12px) translateX(-2px) skew(-20deg);
}
.burger:before {
transform: translateY(-16px) skew(-10deg);
}
<button id="burger" class="navbar-toggler open-main-nav"><span class="burger"></span></button>
<nav class="main-nav" id="main-nav">
<ul>
<li><a href="#home" class="nav-link" title="">home</a></li>
<li><a href="#services" class="nav-link" title="">services</a></li>
<li><a href="#portfolio" class="nav-link" title="">portfolio</a></li>
<li><a href="#about" class="nav-link" title="">about</a></li>
<li><a href="#contacts" class="nav-link" title="">contacts</a></li>
</ul>
</nav>
- 1 回答
- 0 关注
- 74 浏览
添加回答
举报