Sådan oprettes: Dropdown-menu sidebjælke

Lær hvordan du tilføjer en dropdown-menu i side导航.

Dropdown-menu i side导航栏

Try it yourself

Opret en dropdown-menu sidebjælke

Første trin - Tilføj HTML:

<div class="sidenav">
  <a href="#about">About</a>
  <a href="#services">Services</a>
  <a href="#clients">Clients</a>
  <a href="#contact">Contact</a>
  <button class="dropdown-btn">Dropdown
    <i class="fa fa-caret-down"></i>
  </button>
  <div class="dropdown-container">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
  <a href="#contact">Search</a>
</div>

例子解释:

使用任何元素打开下拉菜单,例如 <button>,<a> 或 <p> 元素。

使用容器元素(如 <div>)创建下拉菜单,并在其中添加下拉菜单链接。我们将对侧边栏内的所有链接使用相同的样式。

第二步 - 添加 CSS:

/* 固定的侧边导航栏,全高 */
.sidenav {
  height: 100%;
  width: 200px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  padding-top: 20px;
}
/* 设置侧边栏链接和下拉菜单按钮的样式 */
.sidenav a, .dropdown-btn {
  padding: 6px 8px 6px 16px;
  text-decoration: none;
  font-size: 20px;
  color: #818181;
  display: block;
  border: none;
  background: none;
  width:100%;
  text-align: left;
  cursor: pointer;
  outline: none;
}
/* 鼠标悬停时 */
.sidenav a:hover, .dropdown-btn:hover {
  color: #f1f1f1;
}
/* Main content */
.main {
  margin-left: 200px; /* Same as the width of the sidebar */
  font-size: 20px; /* Increase text size to enable scrolling */
  padding: 0px 10px;
}
/* Add an active class to the active dropdown menu button */
.active {
  background-color: green;
  color: white;
}
/* Dropdown menu container (default is hidden). Optional: Add a brighter background color and some left padding to change the design of the dropdown menu content */
.dropdown-container {
  display: none;
  background-color: #262626;
  padding-left: 8px;
}
/* Optional: Set the style of the downward arrow icon */
.fa-caret-down {
  float: right;
  padding-right: 8px;
}

Try it yourself

Third step - Add JavaScript:

/* Traverse all dropdown menu buttons to toggle between hiding and showing their dropdown menu content - this allows users to have multiple dropdown menus without any conflicts */
var dropdown = document.getElementsByClassName("dropdown-btn");
var i;
for (i = 0; i < dropdown.length; i++) {
  dropdown[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var dropdownContent = this.nextElementSibling;
    if (dropdownContent.style.display === "block") {
      dropdownContent.style.display = "none";
    } else {
      dropdownContent.style.display = "block";
    }
  });
}

Try it yourself

Related pages

Tutorial:CSS dropdown menu

Tutorial:How to create clickable dropdown menus

Tutorial:CSS navigation bar

Tutorial:How to create a sidebar navigation bar