在Sidenav中管理下拉列表

时间:2019-03-01 13:41:10

标签: javascript css

我正在尝试进行以下导航:

  1. 只有一个打开的子列表(关闭其他列表)
  2. 在子列表中仅选择单击的链接

那里有很多示例,但是我在Vanilla Javascript中找不到任何好的示例。

HTML

<div class="sidenav">
  <a href="#">Home</a>
  <button class="btn">Module 1</button>
  <div class="list">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
  <button class="btn">Module 2</button>
  <div class="list">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>

JavaScript

var dropdown = document.getElementsByClassName("btn");
var i;

for (i = 0; i < dropdown.length; i++) {
  dropdown[i].addEventListener("click", function() {
    var dropdownContent = this.nextElementSibling;
    if (dropdownContent.style.display === "block") {
      dropdownContent.style.display = "none";
    } else {
      dropdownContent.style.display = "block";
    }
  });
}

在此小提琴上可以找到完整的CSS:

http://jsfiddle.net/q2en6djg/1/

任何线索,提示或帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

您可以考虑使用一个type Example struct { Example string `json:"example"` Example2 Example2 `json:"example2"` } type Example2 struct { Example3 int64 `json:"example3"` } CSS类来简化它:

active
var dropdown = document.getElementsByClassName("btn");
var l = dropdown.length;
var i;

for (i = 0; i < l; i++) {
  dropdown[i].addEventListener("click", function() {
    for (var j = 0; j < l; j++) {
      if (this != dropdown[j])
        dropdown[j].classList.remove('active')
    }
    this.classList.toggle('active');

  });
}

/*To select the sub item*/
var sub = document.querySelectorAll(".list a");

for (var i = 0; i < sub.length; i++) {
  sub[i].addEventListener("click", function() {
    this.classList.toggle('active');

  });
}
* {
  font-family: "Trebuchet MS", sans-serif;
  font-size: 7em;
}

.sidenav {
  margin-top: 0px;
  height: auto;
  width: 200px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #555;
  overflow-x: hidden;
}

.sidenav a,
.btn {
  padding: 10px 10px 10px 20px;
  text-decoration: none;
  font-size: 17px;
  color: #fff;
  display: block;
  text-align: left;
  border: none;
  background: none;
  width: 100%;
  cursor: pointer;
  outline: none;
  border-bottom: 1px solid #777;
  box-sizing:border-box;
}

.sidenav a:hover,
.sidenav a.active,
.btn:hover,
.btn.active {
  background-color: #777;
}

.list {
  display: none;
  background-color: #999;
  padding-left: 0px;
}

.active+.list {
  display: block;
}