当用户单击汉堡包图标时,我试图显示/隐藏下拉菜单。
当用户单击#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不会变为可见/不可见。
答案 0 :(得分:1)
您只缺少两件事:
将您的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>