gpt4 book ai didi

javascript - 打开和关闭菜单

转载 作者:行者123 更新时间:2023-12-04 08:45:58 26 4
gpt4 key购买 nike

我有 4 个菜单,使用这段代码,我可以显示菜单并使用特定的 btns 隐藏它们。我的问题是,当我打开一个菜单但不关闭它然后打开另一个关闭之前的菜单时,我该怎么办?我试图将打开的菜单存储在一个变量中,并在我打开另一个菜单时检查它,但没有用。

    <body>

<div class="container"> ‌
<div class="menu">
<button class="btn">open</button>
<div class="items">
<div class="items-container">
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 3</div>
<div class="item">item 4</div>
<div class="item">item 6</div>
</div>
</div>
</div>
<div class="container"> ‌
<div class="menu">
<button class="btn">open</button>
<div class="items">
<div class="items-container">
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 3</div>
<div class="item">item 4</div>
<div class="item">item 6</div>
</div>
</div>
</div>
<div class="container"> ‌
<div class="menu">
<button class="btn">open</button>
<div class="items">
<div class="items-container">
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 3</div>
<div class="item">item 4</div>
<div class="item">item 6</div>
</div>
</div>
</div>
<div class="container"> ‌
<div class="menu">
<button class="btn">open</button>
<div class="items">
<div class="items-container">
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 3</div>
<div class="item">item 4</div>
<div class="item">item 6</div>
</div>
</div>
</div>
</div>


</body>

const btns = document.querySelectorAll(".btn");
btns.forEach(btn => {
const menu = btn.parentElement;
const items = menu.querySelector(".items");
const itemsContainer = items.querySelector(".items-container");
const itemsContainerHeight = itemsContainer.getBoundingClientRect().height;
let previousActivebtn = "";

btn.addEventListener("click", (e) => {
// change btn text
if (e.currentTarget.innerHTML == "open") {
e.currentTarget.innerHTML = "close";
} else {
e.currentTarget.innerHTML = "open";
}


//show and hid the menus
if (!items.classList.contains("item-active")) {
items.classList.add("item-active");
items.style.height = itemsContainerHeight + 32 + "px";
} else {
items.classList.remove("item-active");
items.removeAttribute("style");

}


});
});

最佳答案

你把它复杂化了。您可以创建一个 CSS 规则来确保 .items是隐藏的,除非 .menu打开:

.menu .items:not(.open) {
display: none
}
你可以创建一个这样的函数:
function open(item) {
if (!item.classList.contains("open")) {
//Hide whatever was opened
for (let it of document.querySelectorAll(.menu .items.open)) {
it.classList.remove("open")
}
item.classList.add("open");
} else {
item.classList.remove("open");
}
}
只需将具有 items 类的元素传递给此函数.

关于javascript - 打开和关闭菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64325559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com