Tree view cho phép mở/đóng các nhánh lồng nhau. Cần CSS cho giao diện và JavaScript đơn giản để toggle class.
Ví dụ mã nguồn
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
ul, #treeUL { list-style-type: none; }
#treeUL { margin: 0; padding: 0; }
.rootTree {
cursor: pointer;
user-select: none;
font-size: 18px;
font-weight: bold;
color: blue;
}
li { font-size: 16px; color: crimson; font-weight: 500; }
.rootTree::before {
content: "\25B6"; /* Tam giác ▶ */
color: black;
display: inline-block;
margin-right: 6px;
}
.rootTree-down::before {
transform: rotate(90deg); /* Xoay thành ▼ khi mở */
}
.children { display: none; }
.active { display: block; }
</style>
</head>
<body>
<h1>Tree view example</h1>
<ul id="treeUL">
<li>
<span class="rootTree">Root</span>
<ul class="children">
<li>/bin</li>
<li>/etc</li>
<li>
<span class="rootTree">/home</span>
<ul class="children">
<li>/home/Downloads</li>
<li>/home/Pictures/</li>
<li>
<span class="rootTree">/home/Desktop</span>
<ul class="children">
<li>/home/Desktop/file.txt</li>
<li>/home/Desktop/file1.mp3</li>
<li>/home/Desktop/file1.mp4</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<script>
var toggler = document.querySelectorAll(".rootTree");
Array.from(toggler).forEach(item => {
item.addEventListener("click", () => {
item.parentElement.querySelector(".children").classList.toggle("active");
item.classList.toggle("rootTree-down");
});
});
</script>
</body>
</html>
Giải thích
- CSS:
::beforetạo icon mũi tên,.childrenẩn mặc định,.activehiển thị - JS: Duyệt tất cả
.rootTree, gắn sự kiện click toggle class - Đệ quy tự nhiên: Cấu trúc HTML lồng nhau tự xử lý nhiều cấp
Nâng cao
- Thêm animation
transition: max-height 0.3scho mượt - Lưu trạng thái mở/đóng vào localStorage
- Thêm keyboard navigation (Enter/Space để toggle)
- Dùng
<details>+<summary>HTML5 cho bản no-JS