如何使用classList切换显示/隐藏下拉列表内容?

时间:2019-02-04 07:43:49

标签: javascript html css

当用户单击汉堡包图标时,我试图显示/隐藏下拉菜单。

当用户单击#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不会变为可见/不可见。

1 个答案:

答案 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">&#9776;</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>