我在使用这个可折叠组件时遇到了问题。它与 div 有关,因为在 2nd collapsible 上,我删除了包含的 div,它工作正常。有什么问题?
https://codepen.io/TheConnorCraig/pen/eLdaVQ
var coll = document.getElementsByClassName("cbCollapse");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight) {
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
.cbCollapseRow {
display: flex;
}
.cbCollapse {
background-image: url('https://www.pitsco.com/skins/mobile/PlusIcon.svg');
background-size: cover;
cursor: pointer;
padding: 30px;
border: none;
margin-bottom: 15px;
}
.content {
width: 100%;
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
<div class="cbCollapseRow">
<button class="cbCollapse"></button>
<h2>Sample 1</h2>
</div>
<div class="content">
<p>Lorem ipsum dolor sit amet</p>
</div>
<button class="cbCollapse"></button>
<div class="content">
<p>Lorem ipsum dolor sit amet</p>
</div>
<div class="cbCollapseRow">
<button class="cbCollapse"></button>
<h2>Sample 3</h2>
</div>
<div class="content">
<p>Lorem ipsum dolor sit amet</p>
</div>
最佳答案
您的元素未随包含的 div 扩展的原因是 nextElementSibling()
你在瞄准。这导致您的 <h2>
接收最大高度样式。
如果你想把容器都放在上面,你可以把它改成this.parentNode.nextElementSibling;
并且当前代码将起作用。 see this pen
然而,这会破坏未包装的 div。如果您想将它们全部包装起来,这应该不是问题。
关于javascript - 为什么我的折叠器不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52083861/