如何創建:折疊效果

學習如何創建可折疊部分。

可折疊效果

單擊該按鈕可在顯示和隱藏可折疊內容之間切換。

Some collapsible content. Click the button to toggle between showing and hiding the collapsible content. 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.

親自試一試

創建可折疊部分效果

第一步 - 添加 HTML:

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

第二步 - 添加 CSS:

設置手風琴樣式:

/* 設置用于打開和關閉可折疊內容的按鈕的樣式 */
.collapsible {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}
/* 當按鈕被點擊時,以及當您將鼠標移到按鈕上時(懸停),為按鈕添加背景顏色(使用 JS 添加 .active 類) */
.active, .collapsible:hover {
  background-color: #ccc;
}
/* 設置可折疊內容的樣式。注意:默認隱藏 */
.content {
  padding: 0 18px;
  display: none;
  overflow: hidden;
  background-color: #f1f1f1;
}

第三步 - 添加 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: 0overflow: hide 以及 max-height 屬性的過渡添加到面板類中。

然后,使用 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 字符 */
  font-size: 13px;
  color: white;
  float: right;
  margin-left: 5px;
}
.active:after {
  content: "\2796"; /* 表示“減號”(-)的 Unicode 字符 */
}

親自試一試