我试图获得一个可折叠的工作,并遵循了这个例子。我想要其中的几个,其中一些默认情况下应该是活动的。我检查了这个问题,以使默认的打开可折叠运行,它运行得很好,只是CSS转换在第一次尝试时不起作用。
我从上面的问题中分出了jsfiddle,并将其更改为我当前的解决方案。我还增加了过渡时间,以便更好地显示问题。
JSFiddle:https://jsfiddle.net/0q2cko7p/
function toggleCollapsibleSectionWithAnimation() {
this.classList.toggle("collapsible-active");
var buttonId = this.id;
var sectionId = buttonId.replace("button","section");
var content = document.getElementById(sectionId);
if (content.style.maxHeight) {
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
}
/* Style the button that is used to open and close the collapsible content */
.collapsible {
background-color: #777;
color: white;
padding: 10px;
cursor: pointer;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}
/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */
.collapsible-active, .collapsible:hover {
background-color: #444;
}
.collapsible:after {
content: ' 2795'; /* Unicode character for "plus" sign (+) */
font-size: 13px;
color: white;
float: right;
margin-left: 5px;
}
.collapsible-active:after {
content: "2796"; /* Unicode character for "minus" sign (-) */
}
/* Style the collapsible content. Note: hidden by default */
.collapsible-content {
max-height: 0;
padding: 10px;
overflow: hidden;
transition: max-height 0.5s ease-out;
}
<button class="collapsible collapsible-active" id="collapsible-button-0" onclick="toggleCollapsibleSectionWithAnimation.call(this)">
<b>Model</b>
</button>
<div class="collapsible-content" id="collapsible-section-0" style="max-height: 100%">
<h1>
Content Text Content Text Content Text Content Text Content Text Content Text Content Text Content Text Content Text
</h1>
</div>
这是因为.collapsible-content
元素具有最大高度:100%;您需要以像素为单位进行设置。
如果您想要可重用的解决方案,我建议使用数据属性(类似于data-expanded="true"
(来告诉脚本默认情况下扩展哪些节点。这里是示例的链接