一些 Stackoverflow 用户建议使用 classList.toggle 代替 if 和 else 条件。所以我试图让它在我的下拉菜单中工作,但我不明白为什么它不起作用。
以完全随机的方式单击菜单项,我发现自己有div class="drop_container hide show"
,因此类不会像 if 和 else 条件那样交替,但是 drop_container 类正在获取隐藏和显示。有什么不对 ?
编辑:感谢所有用户的评论,我意识到我错了。我得到的答案都是正确的,但没有一个是我的解决方案。最接近我的问题的是用户@jeremy-denis 给出的答案
这是我找到的解决方案:最初我认为需要两个类来为下拉关闭设置动画,最后我意识到只有一个类就足够了。所以我加入transition: max-height 0.3s ease;
了 drop_container 类。
这样我就不再有 classList.toggle 的初始问题。
var dropdownBtn = document.querySelectorAll('.menu-btn');
//Add this for toggling dropdown
lastOpened = null;
dropdownBtn.forEach(btn => btn.addEventListener('click', function() {
var menuContent = this.nextElementSibling;
menuContent.classList.toggle("show");
//Add this for toggling dropdown
if (lastOpened && lastOpened !== menuContent)
lastOpened.classList.remove("show");
lastOpened = menuContent;
}));
.menu-btn {
background: #e0e0e0;
padding: 10px;
margin: 5px 0px 0px 0px;
}
.menu-btn:hover {
background: #000;
color: #fff;
}
.drop_container {
overflow: hidden;
max-height: 0;
transition: max-height 0.2s ease-out;
}
.drop_container.show {
max-height: 300px;
transition: max-height 0.4s ease-in;
}
.drop_container > .item {
display: flex;
flex-direction: column;
margin-left: 10px;
padding: 10px 0px 0px 0px;
}
<div class="dropdown-menu">
<div class="menu-btn">One</div>
<div class="drop_container">
<a class="item" href="#">Contact Us</a>
<a class="item" href="#">Visit Us</a>
</div>
<div class="menu-btn">Two</div>
<div class="drop_container">
<a class="item" href="#">Contact Us</a>
<a class="item" href="#">Visit Us</a>
</div>
</div>
您只需切换类显示即可隐藏和显示不同的元素
menuContent.classList.toggle("show");
var dropdownBtn = document.querySelectorAll('.menu-btn');
//Add this for toggling dropdown
lastOpened = null;
dropdownBtn.forEach(btn => btn.addEventListener('click', function() {
var menuContent = this.nextElementSibling;
menuContent.classList.toggle("show");
//Add this for toggling dropdown
if (lastOpened && lastOpened !== menuContent)
lastOpened.classList.remove("show");
lastOpened = menuContent;
}));
.menu-btn {
background: #e0e0e0;
padding: 10px;
margin: 5px 0px 0px 0px;
}
.menu-btn:hover {
background: #000;
color: #fff;
}
.drop_container {
overflow: hidden;
max-height: 0;
}
.drop_container.show {
max-height: 300px;
transition: max-height 0.3s ease;
}
.drop_container.hide {
overflow: hidden;
max-height: 0;
transition: max-height 0.3s ease;
}
.drop_container>.item {
display: flex;
flex-direction: column;
margin-left: 10px;
padding: 10px 0px 0px 0px;
}
<div class="dropdown-menu">
<div class="menu-btn">One</div>
<div class="drop_container">
<a class="item" href="#">Contact Us</a>
<a class="item" href="#">Visit Us</a>
</div>
<div class="menu-btn">Two</div>
<div class="drop_container">
<a class="item" href="#">Contact Us</a>
<a class="item" href="#">Visit Us</a>
</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句