我有一个简单的下拉菜单使用JavaScript。多个下拉菜单使用相同的JS代码
<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'代码会有帮助。 –