Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

วิธีสร้าง Tree View ด้วย CSS และ JavaScript

Tree View แบบ Collapsible: โครงสร้างโฟลเดอร์/เมนูหลายระดับ

ใช้ nested <ul><li> ร่วมกับ CSS สำหรับไอคอน chevron (▶/▼) และ JavaScript สลับ class .active (แสดง/ซ่อน) และ .rootTree-down (หมุนไอคอน)

โค้ดตัวอย่าง

<!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"; /* ▶ */
      color: black; display: inline-block; margin-right: 6px;
    }
    .rootTree-down::before { transform: rotate(90deg); } /* ▼ */
    .children { display: none; }
    .active { display: block; }
  </style>
</head>
<body>
  <h1>ตัวอย่าง Tree View</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>

การทำงาน

  • คลิกที่ .rootTree (span ที่มี class) จะ toggle class active บน .children ถัดไป
  • 2. พร้อมกันหมุนไอคอน ▶ → ▼ ด้วย class rootTree-down
  • โครงสร้าง nested ul > li > span.rootTree + ul.children รองรับระดับลึกไม่จำกัด

ปรับปรุงเพิ่มเติม

  • เพิ่ม transition: max-height 0.3s ให้ .children เพื่อ animation slide down/up
  • ใช้ details/summary (HTML5 native) แทน JS – เรียบง่ายกว่า แต่ปรับแต่งไอคอนยากกว่า
  • เพิ่ม keyboard navigation (Enter/Space, Arrow keys) เพื่อ accessibility