0
我有很多<ul>
<li>
s和每個<ul>
都有它自己的下拉菜單。我想一次只打開一個下拉菜單。如果我點擊打開一個,那麼已經打開的那個需要關閉。JavaScript如何在另一個點擊打開時關閉一個下拉菜單。沒有Jquery
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>
謝謝,但是當我點擊這個方式它不關閉的相同元素下拉。 – Gabriel747
請你可以建議一些方法使其工作? – Gabriel747
我更新了我的答案,從'overlayOpen'從 –