方法-ツリービュー
CSSとJavaScriptを使用してツリービューを作成する方法を学びます。
ツリー表示
ツリービューは、情報の階層ビューを表します。各アイテムには、いくつかのサブアイテムを含めることができます。
矢印をクリックして、木の枝を開いたり閉じたりします。
- 飲料
- 水
- コーヒー
- お茶
- 紅茶
- 白いお茶
- 緑茶
- 煎茶
- Gyokuro
- 抹茶
- Pi Lo Chun
ツリー表示
ステップ1)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>
ステップ2)CSSを追加します。
例
/* 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;
}
ステップ3)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");
});
}
チェックボックスツリービュー
この例では、キャレットの代わりに「投票箱」ユニコードを使用します。