如何使用班级列表切换显示/隐藏下拉列表中的内容?

问题描述 投票:0回答:1

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

类当用户点击#汉堡包图标.show上#下拉内容切换。切换.show做是为了显示/隐藏#下拉列表内容。

请参考的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");
}

我希望当用户点击图标汉堡包,里面#下拉内容的链接将是可见的,如果它是隐藏的,隐藏的,如果它是可见的。但是#下拉内容不进行对汉堡包图标显示/隐藏,当用户点击。

javascript html css
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.