目录

操作方法 - 折叠


了解如何创建可折叠部分。


可折叠

单击该按钮可在显示和隐藏可折叠内容之间切换。

一些可折叠的内容。单击该按钮可在显示和隐藏可折叠内容之间切换。 Lorem ipsum dolor sat amet,consectetur adipisicing elit,sed do eiusmod tempor incididunt ut laboure et dolore magna aliqua。 Ut enim ad minim veniam, quis nostrud exeritation ullamco labouris nisi ut aliquip ex ea commodo consequat.

亲自试一试 »


创建一个可折叠的

步骤1)添加HTML:

示例

<button type="button" class="collapsible">Open Collapsible</button>
<div class="content">
  <p>Lorem ipsum...</p>
</div>

步骤2)添加CSS:

设计手风琴的样式:

示例

/* Style the button that is used to open and close the collapsible content */
.collapsible {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  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) */
.active, .collapsible:hover {
  background-color: #ccc;
}

/* Style the collapsible content. Note: hidden by default */
.content {
  padding: 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";
    }
  });
}
亲自试一试 »

动画可折叠(向下滑动)

要使动画可折叠,请添加max-height: 0,overflow: hidden和一个transition对于 max-height 属性,panel类。

然后,使用JavaScript通过设置一个计算值来向下滑动内容max-height,取决于不同屏幕尺寸上面板的高度:

示例

<style>
.content {
  padding: 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 character for "plus" sign (+) */
  font-size: 13px;
  color: white;
  float: right;
  margin-left: 5px;
}

.active:after {
  content: "\2796"; /* Unicode character for "minus" sign (-) */
}
亲自试一试 »