我发现了在w3schools上折叠元素的美好前景:https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapsible_symbol
我想还原它,以便在页面加载时显示所有元素,然后使用这个未来在可见/隐藏之间切换。
我有这样的代码:
<style>
.collapsible {
background-color: #777;
color: white;
cursor: pointer;
padding: 5px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 12px;
}
.collapsible:after {
content: '\002B';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}
.collapsible.active:after {
content: "\2212";
}
.content {
padding: 0 20px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
</style>
<script>
$(document).ready(function() {
var coll = document.getElementsByClassName("collapsible");
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";
}
});
}
});
</script>示例如下:https://jsfiddle.net/g50v4cL2/
因此,当页面加载时,我希望它是这样的:

然后就可以崩溃..有人能帮我吗?
谢谢。
发布于 2021-01-21 04:00:34
有很多方法可以做到这一点,在这种情况下,我尽量不做太多的更改,并坚持您已有的方式,因此您只需将active类添加到您的元素中,并将您的js代码更改为如下所示:
var coll = document.getElementsByClassName("collapsible");
var i;
const adjustContentHeight = (content) => {
if (content.style.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
}
for (i = 0; i < coll.length; i++) {
adjustContentHeight(coll[i].nextElementSibling);
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
adjustContentHeight(this.nextElementSibling);
});
}.collapsible {
background-color: #777;
color: white;
cursor: pointer;
padding: 5px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 12px;
}
.collapsible:after {
content: '\002B';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}
.collapsible.active:after {
content: "\2212";
}
.content {
padding: 0 20px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}<button class='collapsible active'>Test1</button>
<div class='content'>
<label><input type = 'checkbox' value = 'value1'/> value1</label>
<label><input type = 'checkbox' value = 'value2'/> value2</label>
<label><input type = 'checkbox' value = 'value3'/> value3</label>
<label><input type = 'checkbox' value = 'value4'/> value4</label>
</div>
<button class='collapsible active'>Test2</button>
<div class='content'>
<label><input type = 'checkbox' value = 'value5'/> value5</label>
<label><input type = 'checkbox' value = 'value6'/> value6</label>
<label><input type = 'checkbox' value = 'value7'/> value7</label>
</div>
如果您不希望在开始时看到此转换,请考虑从css中删除转换属性,并将其添加到此代码之后的js中
https://stackoverflow.com/questions/65816543
复制相似问题