gpt4 book ai didi

javascript - 打开其他下拉菜单时关闭下拉菜单

转载 作者:行者123 更新时间:2023-11-28 04:04:06 25 4
gpt4 key购买 nike

这是我的代码:https://jsfiddle.net/qesr0ybf/

/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction2() {
document.getElementById("myDropdown2").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}

打开一个下拉菜单时,可以同时打开另一个下拉菜单。我正在尝试关闭另一个,一次只打开一个。怎么办?

最佳答案

将您的函数更新为:

function myFunction() {
var d2 = document.getElementById("myDropdown2").classList;
if(d2.contains("show")) d2.toggle("show");
document.getElementById("myDropdown").classList.toggle("show");
}

其他功能类似。

即,检查另一个下拉列表是否包含 show 类,然后将其删除。

更好的方法是跟踪最后打开的下拉列表并在打开另一个下拉列表之前将其关闭,但由于您只有两个下拉列表,所以应该这样做。

现场演示 here

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

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