我发现了在 w3schools 上折叠元素的美好未来:this answer
我想恢复它,以便在加载页面时显示所有元素,然后使用此未来在可见/隐藏之间切换..
我有这个代码:
<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://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapsible_symbol
所以当页面加载时,我希望它是这样的:
https://jsfiddle.net/g50v4cL2/
然后能够崩溃..有人能帮我吗?
谢谢。
答案 0 :(得分:1)
有很多方法可以做到,在这种情况下,我尽量不做太多更改并坚持您的方式,因此您只需将 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>
如果不想一开始就看到这个transition,可以考虑把css中的transition属性去掉,在这段代码后面加到js中