Paano Gumawa: Tree View

Alamin kung paano gumawa ng tree view gamit ang CSS at JavaScript.

Tree View

Ang tree view ay representasyon ng mga kaparehong estraktura ng impormasyon, kung saan ang bawat sangay ay maaaring magkaroon ng maraming mga sangay na anihin.

Kitaang-click ang talon upang buksan o isara ang maganap na sangay.

  • Beverages
    • Water
    • Coffee
    • Tea
      • Black Tea
      • White Tea
      • Green Tea
        • Sencha
        • Gyokuro
        • Matcha
        • Pi Lo Chun

亲自试一试

Tree View

Pangunahing hakbang - Magdagdag ng HTML:

<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>

Second step - 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;
}
/* When the caret/arrow icon is clicked, rotate it (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;
}

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

亲自试一试

Check box tree view

在这个例子中,我们使用一个“投票箱” unicode 而不是 caret:

实例

亲自试一试