【发布时间】:2020-04-06 19:26:04
【问题描述】:
我有一个使用 JavaScript 的简单下拉菜单。
<div id="show-nav" class="dropdown">
<div id="dropdown" onClick="myFunction()">Menu Name</div>
<div id="myDropdown" class="dropdown-content">
<a href="#option1">Option 1</a>
<a href="#option2">Option 2</a>
<a href="#option3">Option 3</a>
</div>
</div>
还有 JS:
<script>
/* 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 menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('#dropdown')) {
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');
}
}
}
}
</script>
我在几个相邻的 div 中有同一个菜单的多个副本。使用此代码,菜单在第一个元素中起作用,但如果我尝试在第二个元素中切换它,它只会在第一个元素中下降。我怎样才能使这适用于单个页面上的多个菜单?
【问题讨论】:
-
html代码会很有帮助。
标签: javascript html dropdown