javascript - 如何使用 classList toggle 来显示/隐藏下拉列表内容?

标签 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 不会变得可见/不可见。

最佳答案

您只遗漏了两件事:

将您的 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>

关于javascript - 如何使用 classList toggle 来显示/隐藏下拉列表内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54511902/

相关文章:

javascript - 如何根据 Jquery 中的屏幕大小移动绝对位置元素

javascript - Datatables 和 ColumnFilterWidgets 的重置链接不会重新填充选择

javascript - VB.NET 中的转义引号 (aspx.vb)

html - 具有动态大小子项的容器的 CSS 滚动

jquery - 修复了封面图像下的导航栏

javascript - 需要将圆形图像分成8个部分,并在每个部分上贴上标签。按下标签会将圆圈转到分开的部分

javascript - Bootstrap 模态有一个缺陷

php - 如何将具有动态大小的图像蒙版到形状?

css - 如何居中 ngx-bootstrap 模态

css - 如何将 CSS Transition 应用于我的响应式菜单?