如何 - 折叠
学习如何创建一个可折叠的部分。
可折叠
点击按钮在显示和隐藏可折叠内容之间切换。
一些可折叠内容。点击按钮在显示和隐藏可折叠内容之间切换。 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
创建可折叠内容
步骤 1) 添加 HTML
示例
<button type="button" class="collapsible">打开可折叠内容</button>
<div class="content">
<p>Lorem ipsum...</p>
</div>
步骤 2) 添加 CSS
样式化手风琴
示例
/* 样式用于打开和关闭可折叠内容的按钮 */
.collapsible {
background-color: #eee;
颜色: #444;
cursor: pointer;
填充: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
字体大小: 15px;
}
/* 如果按钮被点击(通过 JS 添加 .active 类),并且鼠标悬停在按钮上时,添加背景颜色 */
.active, .collapsible:hover {
background-color: #ccc;
}
/* 样式化可折叠内容。注意:默认隐藏 */
.content {
填充: 0 18px;
display: none;
overflow: hidden;
background-color: #f1f1f1;
}
步骤 3) 添加 JavaScript
示例
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.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
自己动手试一试 »
动画可折叠内容(滑动展开)
要创建动画可折叠内容,请为 panel
类添加 max-height: 0
、overflow: hidden
以及 max-height
属性的 transition
。
然后,使用 JavaScript 通过设置一个计算出的 max-height
值来滑动展开内容,该值取决于不同屏幕尺寸下面板的高度。
示例
<style>
.content {
填充: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
</style>
<script>
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>
自己动手试一试 »
添加图标
在每个按钮上添加一个符号,以指示可折叠内容是打开还是关闭。
示例
.collapsible:after {
content: '\02795'; /* Unicode 字符表示“加号” (+) */
字体大小: 13px;
color: white;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2796"; /* Unicode 字符表示“减号” (-) */
}
自己动手试一试 »