本章节我们将学习如何使用 JS/CSS 实现手风琴折叠效果。 先看下效果如下:
- <button class="accordion">cdsy 1</button>
- <div class="panel">
- <p>城东书院 -- 学习、工作、生活</p>
- </div>
-
- <button class="accordion">cdsy 2</button>
- <div class="panel">
- <p>城东书院 -- 学习、工作、生活</p>
- </div>
-
- <button class="accordion">cdsy 3</button>
- <div class="panel">
- <p>城东书院 -- 学习、工作、生活</p>
- </div>
以下是手风琴折叠的样式:
- /* 打开和关闭手风琴面板的样式 */
- .accordion {
- background-color: #eee;
- color: #444;
- cursor: pointer;
- padding: 18px;
- width: 100%;
- text-align: left;
- border: none;
- outline: none;
- transition: 0.4s;
- }
-
- /* 设置点击和鼠标移到选项上面时(悬停)的样式 */
- .active, .accordion:hover {
- background-color: #ccc;
- }
-
- /* 为手风琴面板设计样式。 默认隐藏 */
- .panel {
- padding: 0 18px;
- background-color: white;
- max-height: 0;
- overflow: hidden;
- transition: max-height 0.2s ease-out;
- }
- /* 设置 +、- 标志 */
- .accordion:after {
- content: '\002B'; /* Unicode 字符 + 号 */
- color: #777;
- font-weight: bold;
- float: right;
- margin-left: 5px;
- }
-
- .active:after {
- content: "\2212"; /* Unicode 字符 - 号 */
- }
以下是手风琴折叠的 JavaScript 代码:
- var acc = document.getElementsByClassName("accordion");
- var i;
-
- for (i = 0; i < acc.length; i++) {
- acc[i].addEventListener("click", function() {
- this.classList.toggle("active");
- var panel = this.nextElementSibling;
- if (panel.style.maxHeight) {
- panel.style.maxHeight = null;
- } else {
- panel.style.maxHeight = panel.scrollHeight + "px";
- }
- });
- }