我有一个带有多个按钮的垂直边栏导航菜单,每个按钮都包含一个下拉菜单。单击一个按钮可在导航菜单(例如TF000120)中显示锚链接的下拉列表,并在主要内容区域的导航菜单右侧显示一个div(例如“森林”)。目前,如果我单击一个按钮,则其div和下拉列表都可以正常显示。但是,如果在关闭第一个按钮之前单击另一个按钮,则会同时打开div和下拉列表集。在显示新的div和下拉链接之前,如何单击另一个按钮,再次隐藏当前打开的div和下拉链接?
我在W3上使用过this教程。
HTML(导航菜单)
<nav class="sidenav">
<a href="#theforest" class="dropdown-btn" onclick="toggle_visibility('theforest');">The Forest
</a>
<div class="dropdown-container">
<a class="entry-num" href="#TF000120">[TF000120]</a>
<a class="entry-num" href="#TF000220">[TF000220]</a>
<a class="entry-num" href="#TF000320">[TF000320]</a>
</div>
<a href="#theocean" class="dropdown-btn" onclick="toggle_visibility('theocean');">The Ocean</a>
<div class="dropdown-container" >
<a class="entry-num" href="#TO000120">[TO000120]</a>
<a class="entry-num" href="#TO000220">[TO000220]</a>
<a class="entry-num" href="#TO000320">[TO000320]</a>
</div>
<a href="#thesky" class="dropdown-btn" onclick="toggle_visibility('thesky');">The Sky</a>
<div class="dropdown-container" >
<a class="entry-num" href="#TS000120">[TS000120]</a>
<a class="entry-num" href="#TS000220">[TS000220]</a>
<a class="entry-num" href="#TS000320">[TS000320]</a>
</div>
</nav>
JS
<script>
var dropdown = document.getElementsByClassName("dropdown-btn");
var i;
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", function() {
this.classList.toggle("active");
var dropdownContent = this.nextElementSibling;
if (dropdownContent.style.display === "block") {
dropdownContent.style.display = "none";
} else {
dropdownContent.style.display = "block";
}
});
}
</script>
<!--Toggle Function-->
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
谢谢!
答案 0 :(得分:1)
在显示新的下拉菜单之前,请重置所有点击的样式:
dropdown[i].addEventListener("click", function() {
//hide all divs that may be visible
var lst = document.getElementsByClassName("dropdown-containder");
for (var j = 0; j < lst.length; j++) { lst[j].style.display = "none";}
//show the dive that the user selected
this.classList.toggle("active");
var dropdownContent = this.nextElementSibling;
if (dropdownContent.style.display === "block") {
dropdownContent.style.display = "none";
} else {
dropdownContent.style.display = "block";
}
});
}