JavaScript如何在另一个单击打开时关闭一个下拉列表。没有Jquery

时间:2016-08-02 17:17:26

标签: javascript

我有很多<ul> <li>个,每个<ul>都有自己的下拉列表。我希望一次只打开一个下拉菜单。如果我点击打开一个,那么已打开的那个需要关闭。

function toggleClass(element, className) {
  if (!element || !className) {
    return;
  }

  var classString = element.className,
    nameIndex = classString.indexOf(className);
  if (nameIndex == -1) {
    classString += ' ' + className;
  } else {
    classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length);
  }
  element.className = classString;
}

function dropDown(el) {
  toggleClass(el.nextElementSibling, 'overlayOpen');

}
ul {
  width: 200px;
}
li {
  margin: 0;
  font-size: 20px;
  line-height: 50px;
  width: 100%;
  cursor: pointer;
  background-color: red;
  overflow: hidden;
}
.overlayOpen {
  opacity: 1 !important;
  height: 50px !important;
  width: 100% !important;
}
.overlay {
  width: 100%;
  z-index: 1000;
  background-color: green;
  overflow: hidden;
  max-width: 800px;
  opacity: 0;
  height: 0;
  width: 0;
  -webkit-transition: width 0.2s, height 0.2s, opacity 0.2s ease;
  -moz-transition: width 0.2s, height 0.2s, opacity 0.2s ease;
  -o-transition: width 0.2s, height 0.2s, opacity 0.2s ease;
  -ms-transition: width 0.2s, height 0.2s, opacity 0.2s ease;
  transition: width 0.2s, height 0.2s, opacity 0.2s ease;
}
<ul>
  <li id="1" onclick='dropDown(this)'>example</li>
  <li id="overlay_1" class='overlay'>Hidden stuff</li>
</ul>

<ul>
  <li id="2" onclick='dropDown(this)'>example</li>
  <li id="overlay_2" class='overlay'>Hidden stuff</li>
</ul>

1 个答案:

答案 0 :(得分:0)

您可以在打开单击元素之前从所有元素中删除overlayOpen类:

function dropDown(el) {
  Array.from(document.querySelectorAll('.overlayOpen'))
       .filter(elem => elem !== el.nextElementSibling)
       .forEach(element => element.classList.remove('overlayOpen'));
  toggleClass(el.nextElementSibling, 'overlayOpen');
}