今天给自己的归档用上手风琴效果,就简单利用了网格的 grid-template-rows
属性,下面是基本的步骤。
因为要用到 jquery 语法,所以先引入 jquery.js 库
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.min.js"></script>
一、html 代码
<div class="accordion">
<div class="accordion-title">手风琴效果</div>
<div class="accordion-body">
<div>
手风琴内容<br>
手风琴内容<br>
手风琴内容<br>
</div>
</div>
<div class="accordion-title">手风琴效果</div>
<div class="accordion-body">
<div>
手风琴内容<br>
手风琴内容<br>
手风琴内容<br>
</div>
</div>
</div>
二、添加 CSS
/* 手风琴效果 */
.accordion {
display: flex;
flex-direction: column;
box-sizing: border-box;
}
.accordion-title {
font-weight: 700;
font-size: 1.5rem;
padding: 1rem;
cursor: pointer;
border: 1px solid gainsboro;
border-radius: 0.4rem;
margin: 0.25rem;
}
.dark .accordion-title {
border: 1px solid gray;
}
.accordion-body {
display: grid;
grid-template-rows: 0fr;
transition: 250ms grid-template-rows ease;
}
.accordion-body * {
margin: 0.25rem 0.25rem;
overflow: hidden;
}
.accord-open+.accordion-body {
grid-template-rows: 1fr;
}
.accord-open::before {
content: "▼ ";
}
.accordion-title:not(.accord-open)::before {
content: "▶ ";
}
三、添加 jQuery 事件
// jqurey 手风琴事件
$(function () {
$(".accordion-title").click(function () {
if ($(this).hasClass("accord-open")) {
$(this).removeClass("accord-open");
} else {
$(this).parent().children().removeClass("accord-open");
$(this).addClass("accord-open");
}
});
});