2 回答
TA贡献1900条经验 获得超5个赞
您的问题是,您正在元素内部的按钮上查找,因此旁边没有任何同级按钮:this.nextElementSibling
<p>
按钮是他父母里面的一个孤独的孩子,所以没有兄弟姐妹。<p>
你有你的代码的方式,容易的事情是寻找兄弟姐妹,所以:<p>
var acc = document.getElementsByClassName("accordion");
var panel = document.getElementsByClassName('panel');
for (var i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
var setClasses = !this.classList.contains('active');
setClass(acc, 'active', 'remove');
setClass(panel, 'show', 'remove');
if (setClasses) {
this.classList.toggle("active");
this.parentNode.nextElementSibling.classList.toggle("show", 800); // nextElementSibling of the parentNode.
}
}
}
function setClass(els, className, fnName) {
for (var i = 0; i < els.length; i++) {
els[i].classList[fnName](className);
}
}
div.panel {
display: none;
transition: 4.6 ease-in-out;
overflow: hidden;
}
div.panel.show {
display: block !important;
<p><button class="accordion">▼ Title 1</button></p>
<div class="panel">
<ul>
<li>
Title
<ul>
<li>Lorem</li>
<li>aaaaa</li>
</ul>
</ul>
</div>
<p><button class="accordion">▼ Title 2</button></p>
<div class="panel">
<ul>
<li>
Title
<ul>
<li>Lorem 1</li>
<li>aaaaa</li>
</ul>
</ul>
</div>
TA贡献1876条经验 获得超6个赞
您的代码有效!仅更改 HTML,如下所示:
<div>
<button class="accordion">▼ Title 1</button>
<div class="panel">
<ul>
<li>
Title
<ul>
<li>Lorem</li>
<li>aaaaa</li>
</ul>
</ul>
</div>
</div>
<div>
<button class="accordion">▼ Title 2</button>
<div class="panel">
<ul>
<li>
Title
<ul>
<li>Lorem 1</li>
<li>aaaaa</li>
</ul>
</ul>
</div>
</div>
添加回答
举报