【发布时间】:2020-02-19 20:03:52
【问题描述】:
我有多个按钮,当您单击一个按钮时菜单会下拉,并且所有其他下拉菜单都将关闭。为此,我目前有 9 个和相应的 9 个函数:
function myFunction5() {
document.getElementById("myDropdown1").classList.remove("show");
document.getElementById("myDropdown2").classList.remove("show");
document.getElementById("myDropdown3").classList.remove("show");
document.getElementById("myDropdown4").classList.remove("show");
document.getElementById("myDropdown5").classList.toggle("show");
document.getElementById("myDropdown6").classList.remove("show");
document.getElementById("myDropdown7").classList.remove("show");
document.getElementById("myDropdown9").classList.remove("show"); }
这会打开下拉菜单 5 并关闭所有其他菜单。
我希望只有一个功能而不是 9 个。我该怎么做?
编辑:
完整的代码示例:
<!DOCTYPE html>
<html>
<head>
<style>
.dropbtn {
background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #ddd;}
.show {display: block;}
</style>
</head>
<body>
<div class="dropdown">
<button onclick="myFunction1()" class="dropbtn">Dropdown</button>
<div id="myDropdown1" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
</div>
<div class="dropdown">
<button onclick="myFunction2()" class="dropbtn">Dropdown</button>
<div id="myDropdown2" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
</div>
<script>
function myFunction1() {
document.getElementById("myDropdown1").classList.toggle("show");
document.getElementById("myDropdown2").classList.remove("show");
}
function myFunction2() {
document.getElementById("myDropdown1").classList.remove("show");
document.getElementById("myDropdown2").classList.toggle("show");
}
</script>
</body>
</html>
想象这 9 次......
【问题讨论】:
-
你能分享任何展示此功能演示的 jsfiddle 吗?
标签: javascript html drop-down-menu dropdown