Cách thực hiện - Thu gọn
Tìm hiểu cách tạo một phần có thể thu gọn.
Có thể thu gọn
Bấm vào nút để chuyển đổi giữa hiển thị và ẩn nội dung có thể thu gọn.
Một số nội dung có thể thu gọn. Bấm vào nút để chuyển đổi giữa hiển thị và ẩn nội dung có thể thu gọn. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labe et dolore magna aliqua. Với một mục tiêu tối thiểu là có thể làm được, điều này sẽ không xảy ra khi bạn phải làm việc quá sức để có được một giải pháp sau mỗi giao dịch.
Tạo một cái có thể thu gọn
Bước 1) Thêm HTML:
Ví dụ
<button type="button" class="collapsible">Open Collapsible</button>
<div class="content">
<p>Lorem ipsum...</p>
</div>
Bước 2) Thêm CSS:
Tạo kiểu cho đàn accordion:
Ví dụ
/* 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;
}
Bước 3) Thêm JavaScript:
Ví dụ
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";
}
});
}
Hãy tự mình thử »Hoạt hình có thể thu gọn (Trượt xuống)
Để tạo hoạt ảnh có thể thu gọn, hãy thêm max-height: 0
, overflow: hidden
và transition
cho thuộc tính max-height vào lớp panel
.
Sau đó, sử dụng JavaScript để trượt nội dung xuống bằng cách đặt max-height
được tính toán, tùy thuộc vào chiều cao của bảng trên các kích thước màn hình khác nhau:
Ví dụ
<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>
Hãy tự mình thử »Thêm biểu tượng
Thêm ký hiệu vào mỗi nút để cho biết nội dung có thể thu gọn đang mở hay đóng:
Ví dụ
.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 (-) */
}
Hãy tự mình thử »