我如何通過點擊另一個來關閉下拉菜單? 當我點擊下拉菜單時,它會打開,然后我點擊另一個,打開的菜單不會關閉。請幫助我
HTML:
`<div class="dropdown">
<button onclick="myFunction(this)"; class="buy-room-button hero-section-button">
Buy room <img src="icons/arrow-down-black.png" alt="">
</button>
<div id="myDropdown" class="dropdown-content">
<a href="#">Link1</a>
<a href="#">Link1</a>
<a href="#">Link1</a>
</div>
</div>`
Java Script語言
function myFunction(a) {
a.parentNode.getElementsByClassName("dropdown-content")[0].classList.toggle("show");
}
onclick = function(event) {
if(!event.target.matches('.hero-section-button')) {
let dropdowns = document.getElementsByClassName('dropdown-content');
let i;
for (i = 0; i < dropdowns.length; i++) {
let openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}