本章节我们将学习如何使用 JS/CSS 实现手风琴折叠效果。
先看下效果如下:
基础 HTML 代码
实例
button class=“accordion“>Runoob 1button>
div class=“panel“>
p>菜鸟教程 — 学的不仅是技术,更是梦想!!!p>
div> button class=“accordion“>Runoob 2button>
div class=“panel“>
p>菜鸟教程 — 学的不仅是技术,更是梦想!!!p>
div> button class=“accordion“>Runoob 3button>
div class=“panel“>
p>菜鸟教程 — 学的不仅是技术,更是梦想!!!p>
div>
div class=“panel“>
p>菜鸟教程 — 学的不仅是技术,更是梦想!!!p>
div> button class=“accordion“>Runoob 2button>
div class=“panel“>
p>菜鸟教程 — 学的不仅是技术,更是梦想!!!p>
div> button class=“accordion“>Runoob 3button>
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 字符 – 号 */
}
.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“;
}
});
}
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“;
}
});
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)