如何使用 CSS 和 JavaScript 创建树状视图?
在一个网页上,如果你想要展示文件夹视图,如同在网络托管文件中展示那样,那么就创建一个树状视图。在树状视图中,根或主目录总是可单击的。我们使用 cursor 属性将值设为 pointer 来设置它可单击。单击时箭头键会旋转 90 度。这是使用 transform 属性中的 rotate() 方法实现的。
设置树状视图的根
使用 <ul> 设置树状视图的根。 在其中,设置 <span> −
<ul id="treeUL">
<li>
<span class="rootTree">Root</span>
<!-- set other tree view root and children -->
</li>
</ul>
设置树状视图的根样式。将光标设置为 pointer,以使根看起来像是可单击的 −
.rootTree {
cursor: pointer;
user-select: none;
font-size: 18px;
font-weight: bold;
color: blue;
}
在根中设置树状视图的子内容
使用 <ul> 设置子内容−
<ul class="children"> <li>/bin</li> <li>/etc</li> </ul>
根的箭头键
要设置箭头键,请使用 content 属性并在其中提及代码 −
.rootTree::before {
content: "\25B6";
color: black;
display: inline-block;
margin-right: 6px;
}
点击根
点击根后,它会旋转,因为 rotate() 方法已经设置为 90 度 −
.rootTree-down::before {
transform: rotate(90deg);
}
示例
要使用 CSS 和 JavaScript 创建树状视图,代码如下 −
<!DOCTYPE html>
<html>
<head>
<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 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>
debugger;
console.log('wow');
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>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP