1 回答
TA贡献1820条经验 获得超2个赞
尝试在 mobileMenu div 上设置 hidden 属性,并在单击按钮时相应更新。这样你就可以避免弄乱 css 类
const openBtn = document.querySelector('.open');
const closeBtn = document.querySelector('.close');
const mobileMenu = document.getElementById('mobileMenu');
openBtn.addEventListener('click', e => {
mobileMenu.hidden = false;
//mobileMenu.classList.add('active');
openBtn.style.display = 'none';
closeBtn.style.display = 'block';
});
closeBtn.addEventListener('click', e => {
//mobileMenu.classList.remove('active');
mobileMenu.hidden = true;
openBtn.style.display = 'block';
closeBtn.style.display = 'none';
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
position: relative;
}
/* Header */
header {
display: flex;
justify-content: space-around;
align-items: center;
padding: .5rem;
height: 60px;
position: fixed;
top: 0;
left: 0;
right: 0;
}
header h2 {
font-family: 'Calistoga';
letter-spacing: 2px;
}
header i {
font-size: 1.5rem;
}
header i:hover {
cursor: pointer;
}
header i.close {
display: none;
}
/* Mobile Nav */
#mobileMenu {
padding: .8rem 0;
border-top: 1px solid #000;
border-bottom: 1px solid #000;
position: fixed;
top: 92px;
left: 0;
right: 0;
overflow: hidden;
transition: height .7s ease-in-out;
}
#mobileMenu.hidden {
height: 0;
line-height: 0;
display: block;
}
#mobileMenu.active {
height: 154px;
}
.mobile-nav {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
list-style: none;
}
.mobile-nav li {
padding: .3rem 0;
}
.mobile-nav li a {
text-decoration: none;
font-size: 1.2rem;
color: #000;
}
<header>
<h2>Website Header</h2>
<i class="fas fa-chevron-down open"></i>
<i class="fas fa-chevron-up close"></i>
</header>
<div id="mobileMenu" hidden>
<ul class="mobile-nav">
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">Services</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
</ul>
</div>
添加回答
举报