我试图在用户点击汉堡包图标时显示/隐藏下拉菜单。
当用户点击#hamburger-icon 时,.show 类会在#dropdown-content 上切换。切换 .show 是为了显示/隐藏 #dropdown-content。
请引用jsfiddle:https://jsfiddle.net/d8oubjmk/1/
相关JS代码为:
// Get the button, and when the user clicks on it, execute myFunction
document.getElementById("hamburger-icon").onclick = function() {myFunction()};
/* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */
function myFunction() {
document.getElementById("dropdown-content").classList.toggle("show");
}
我希望当用户单击汉堡包图标时,#dropdown-content 中的链接如果隐藏则可见,如果可见则隐藏。但是当用户点击汉堡包图标时,#dropdown-content 不会变得可见/不可见。
最佳答案
您只遗漏了两件事:
将您的 JS 代码包装在 window.onload
中,以确保在您尝试选择 DOM 元素之前实际加载它们。
window.onload = () => {
// Get the button, and when the user clicks on it, execute myFunction
document.getElementById("hamburger-icon").onclick = function() {myFunction()};
/* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */
function myFunction() {
document.getElementById("dropdown-content").classList.toggle("show");
}
}
您的 .show
类需要更具体,否则它会失去对 #dropdown-content
的特殊性并且没有任何效果。
/* Applies to elements that have id="dropdown-content" and class="show" */
#dropdown-content.show
{
display: block;
}
这是您的代码:
window.onload = () => {
// Get the button, and when the user clicks on it, execute myFunction
document.getElementById("hamburger-icon").onclick = function() {myFunction()};
/* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */
function myFunction() {
document.getElementById("dropdown-content").classList.toggle("show");
}
}
#dropdown-content a
{
text-decoration:none;
display:block;
}
#dropdown-content {
display: none;
}
#dropdown-content.show
{
display: block;
}
<div id="top-menu">
<div id="hamburger-icon">☰</div>
<div id="dropdown-content" class="show-hide-menu">
<a href="#">Home</a>
<a href="#">Menu1</a>
<a href="#">Menu2</a>
<a href="#">Menu3</a>
<a href="#">About Us</a>
</div>
</div>
关于javascript - 如何使用 classList toggle 来显示/隐藏下拉列表内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54511902/