如何创建:树形视图

学习如何使用 CSS 和 JavaScript 创建树形视图。

树形视图

树形视图表示信息的层次结构视图,其中每个项目可以有多个子项目。

单击箭头可展开或收起树分支。

  • 饮料
    • 咖啡
      • 红茶
      • 白茶
      • 绿茶
        • 煎茶
        • 玉露
        • 抹茶
        • 碧螺春

Try it yourself

树形视图

第一步 - 添加 HTML:

<ul id="myUL">
  <li><span class="caret">饮料</span>
    <ul class="nested">
      <li>水</li>
      <li>咖啡</li>
      <li><span class="caret">茶</span>
        <ul class="nested">
          <li>红茶</li>
          <li>白茶</li>
          <li><span class="caret">绿茶</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>

Step 2 - Add CSS:

/* Remove the default list item symbol */
ul, #myUL {
  list-style-type: none;
}
/* Remove the margin and padding of the parent ul */
#myUL {
  margin: 0;
  padding: 0;
}
/* Set the style of the caret/arrow */
.caret {
  cursor: pointer;
  user-select: none; /* Prevent text selection */
}
/* Use unicode to create the caret/arrow and set its style */
.caret::before {
  content: "\25B6";
  color: black;
  display: inline-block;
  margin-right: 6px;
}
/* Rotate it when the caret/arrow icon is clicked (using JavaScript) */
.caret-down::before {
  transform: rotate(90deg);
}
/* Hide the nested list */
.nested {
  display: none;
}
/* When the user clicks the caret/arrow, display the nested list (using JavaScript) */
.active {
  display: block;
}

Step 3 - Add JavaScript:

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");
  });
}

Try it yourself

Checkbox tree view

In this example, we use a 'ballot box' unicode instead of caret:

Example

Try it yourself