CÁCH THỨC - Chế độ xem dạng cây
Tìm hiểu cách tạo chế độ xem dạng cây bằng CSS và JavaScript.
Chế độ xem cây
Chế độ xem dạng cây đại diện cho chế độ xem thông tin có thứ bậc, trong đó mỗi mục có thể có một số subitem.
Bấm vào (các) mũi tên để mở hoặc đóng các cành cây.
- Đồ uống
- Nước uống
- Cà phê
- Trà
- Trà đen
- Trà trắng
- Trà xanh
- Sencha
- Gyokuro
- Matcha
- Pi Lo Chun
Chế độ xem cây
Bước 1) Thêm HTML:
Thí dụ
<ul id="myUL">
<li><span class="caret">Beverages</span>
<ul class="nested">
<li>Water</li>
<li>Coffee</li>
<li><span
class="caret">Tea</span>
<ul
class="nested">
<li>Black Tea</li>
<li>White Tea</li>
<li><span class="caret">Green Tea</span>
<ul class="nested">
<li>Sencha</li>
<li>Gyokuro</li>
<li>Matcha</li>
<li>Pi Lo Chun</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
Bước 2) Thêm CSS:
Thí dụ
/* Remove default bullets */
ul, #myUL {
list-style-type: none;
}
/* Remove margins and padding from the parent ul */
#myUL {
margin: 0;
padding: 0;
}
/* Style the caret/arrow */
.caret {
cursor: pointer;
user-select: none; /* Prevent text selection */
}
/* Create the caret/arrow with a unicode, and
style it */
.caret::before {
content: "\25B6";
color: black;
display: inline-block;
margin-right: 6px;
}
/* Rotate the
caret/arrow icon when clicked on (using JavaScript) */
.caret-down::before {
transform: rotate(90deg);
}
/* Hide the nested list */
.nested {
display: none;
}
/* Show the nested list when the user clicks on the caret/arrow (with
JavaScript) */
.active {
display: block;
}
Bước 3) Thêm JavaScript:
Thí dụ
var toggler = document.getElementsByClassName("caret");
var i;
for
(i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click",
function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
Hộp kiểm Chế độ xem dạng cây
Trong ví dụ này, chúng tôi sử dụng unicode "hộp phiếu" thay vì dấu mũ: