我不太熟悉 JavaScript,我希望能得到一些帮助来解决我似乎无法解决的问题。目前我的网站上有 2 个下拉菜单。一种是用于导航的下拉菜单,单击汉堡菜单图标时会激活该菜单。第二个下拉列表用于显示我网站上的类别。目前,当我单击一个下拉列表时,我必须再次单击它才能将其关闭。如果我单击第二个下拉菜单而不关闭第一个下拉菜单,则两个下拉菜单都将保持可见。我希望发生的是两件事。首先,我希望如果用户单击 div 之外的任何位置来获取下拉菜单,它会自动关闭。我希望看到发生的第二件事是一次只有一个下拉菜单可见。因此,如果我单击一个下拉列表并打开另一个下拉列表,我希望将其关闭。希望我能很好地解释这一点。现在来看我正在使用的代码。
以下是我脑子里的内容。
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function DropDownMenuNavigation() {
document.getElementById("b2DropDownMenuNav").classList.toggle("show");
}
function DropDownMenuCategory() {
document.getElementById("b2DropDownMenuCat").classList.toggle("show");
}
</script>
然后我使用它作为激活导航下拉菜单的按钮。这已经包含在我的身体里了。
<div class="dropbtn" style="float: left;">
<button onclick="DropDownMenuNavigation()" class="dropbtn">☰ MENU</button>
</div>
这就是我用来包含我的类别下拉菜单的内容。
<div class="dropbtn" style="float: left;">
<button onclick="DropDownMenuCategory()" class="dropbtn">CATEGORIES</button>
</div>
现在最后是我使用的CSS,只是偶尔有帮助。
/* Dropdown Button */
.dropbtn {
background-color: #0066a2;
color: white;
padding: 1px;
font-size: 15px;
font-weight: bold;
border: none;
cursor: pointer;
}
.dropbtn a {
color: #FFFFFF;
text-decoration: none;
font-size: 15px;
font-weight: bold;
}
/* The container <div> - needed to position the dropdown content */
.dropdown {
float: left;
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #0066a2;
min-width: 260px;
max-width: 960px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
/* Links inside the dropdown */
.dropdown-content a {
color: #000000;
text-decoration: none;
}
/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}
那么,完成我所要求的事情的最佳方法是什么?有人可以帮我一把并指出我正确的方向吗?非常感谢,我很感谢你能给我提供的任何帮助。