我试图通过w3schools.com上的本教程使用 Javascript 实现打开和关闭下拉菜单的方法。虽然“显示”下拉菜单的功能有效,但关闭它的功能却不起作用。此外,此代码旁边没有解释来解释为什么它应该工作,这使得调试变得困难。
/* 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('.dropbtn')) {
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');
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,我的问题是,
1) 教程中的代码是否应该用于关闭下拉菜单。(已回答) …