gpt4 book ai didi

javascript - 如何在打开另一个下拉菜单时关闭下拉菜单?

转载 作者:行者123 更新时间:2023-11-28 00:05:22 27 4
gpt4 key购买 nike

我是 javascript 的新手,我的代码需要帮助。

我有两个下拉菜单,其中包含一个按钮和一个带有链接的容器。如何在打开另一个的同时关闭一个下拉菜单?

我尝试比较给他们不同的 ID 并比较它们,但我不确定我做对了。

// achieve effect

// event delegation on body
let activeDropDown;
document.body.addEventListener('click', dropDown);

// event function for toggling class
function dropDown(ex) {
// if (activeDropDown.id && activeDropDown.id !== ex.target.id) {
// activeDropDown.nextElementSibling.classList.toggle('shower');
// }

if(ex.target.parentElement.classList.contains('am')) {
let val;
activeDropDown = ex.target.parentElement.id;
activeDropDown.element = ex.target.parentElement;
val = activeDropDown;
ex.target.nextElementSibling.classList.toggle('shower');
console.log(val);
}
}
// close the dropdown if the user click outside the button
window.addEventListener('click', closeDropDown);
// declaring the function
function closeDropDown(ex2) {
if (!ex2.target.matches('.arch-button')) {
// getting the dropdowncontent
let postDrop = document.querySelectorAll('.monthly-post');
// var i;
for (let i = 0; i < postDrop.length; i++) {
let checkDropDown = postDrop[i];
if (checkDropDown.classList.contains('shower')) {
checkDropDown.classList.remove('shower');
}
}
}
};
 .am:not(:last-child) {
border-bottom: 0.5px solid #C8C8C8;
}
.am:not(:first-child) {
margin-top: 12px;
}
.monthly-post {
position: relative;
left: 17px;
overflow: hidden;
height: 0;

}
.shower{
overflow: visible !important;
max-height: 100% !important;
height: 100% !important;
transition: all ease-in-out 500ms;
-webkit-transition: all ease-in-out 500ms;
-moz-transition: all ease-in-out 500ms;
-ms-transition: all ease-in-out 500ms;
-o-transition: all ease-in-out 500ms;
}
.post-linker {
display: block;
color: #0069E6;
}
.post-linker:hover,
.post-linker:active{
color: #21293C;
}
 <div class="am" id="am-march">
<button class="arch-button">March 2019</button>
<div class="monthly-post">
<a href="" class="post-linker">TEF Application 2019</a>
<a href="" class="post-linker">Big Brother 2019</a>
<a href="" class="post-linker">Hotelo new Application for guest</a>
<a href="" class="post-linker">Air peace easter promo</a>
</div>
</div>
<div class="am" id="am-april">
<button class="arch-button">April 2019</button>
<div class="monthly-post">
<a href="" class="post-linker">ahahahah</a>
<a href="" class="post-linker">ahahahah</a>
<a href="" class="post-linker">ahahaha</a>
<a href="" class="post-linker">ahahahahha</a>
</div>
</div>
我希望在打开另一个下拉菜单时关闭下拉菜单。

最佳答案

您可以使用 event.pathevent.composedPath 检查元素是否不同,并关闭其他下拉菜单。

关于javascript - 如何在打开另一个下拉菜单时关闭下拉菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55731471/

27 4 0