前端编写一个权限树状图
时间: 2023-07-01 16:08:07 浏览: 43
权限树状图通常用于展示系统中的权限结构,让用户更好地了解和管理权限。下面是使用 HTML、CSS 和 JavaScript 编写一个简单的权限树状图的示例代码:
HTML 代码:
```
<div class="tree">
<ul>
<li>
<span class="node">权限 1</span>
<ul>
<li>
<span class="node">子权限 1.1</span>
</li>
<li>
<span class="node">子权限 1.2</span>
</li>
<li>
<span class="node">子权限 1.3</span>
</li>
</ul>
</li>
<li>
<span class="node">权限 2</span>
<ul>
<li>
<span class="node">子权限 2.1</span>
</li>
<li>
<span class="node">子权限 2.2</span>
</li>
</ul>
</li>
</ul>
</div>
```
CSS 代码:
```
.tree ul {
margin: 0;
padding: 0;
list-style-type: none;
}
.tree .node {
cursor: pointer;
}
.tree li {
margin: 0;
padding: 0 1em;
line-height: 2em;
color: #333;
position: relative;
}
.tree li:before, .tree li:after {
content: '';
left: -0.5em;
position: absolute;
right: auto;
}
.tree li:before {
border-left: 1px solid #999;
bottom: 50%;
height: 50%;
top: 0;
}
.tree li:after {
border-top: 1px solid #999;
height: 2em;
top: 25px;
}
.tree li:last-child:before {
height: 25px;
}
.tree ul ul:before {
content: '';
height: 2em;
left: -0.5em;
position: absolute;
top: 25px;
width: 1em;
}
.tree li li:after {
border-top: 1px solid #999;
height: 2em;
top: 25px;
}
.tree li li:last-child:before {
height: 25px;
}
.tree .node {
background-color: #fff;
border: 1px solid #999;
border-radius: 5px;
display: inline-block;
padding: 0.2em 0.5em;
}
.tree .node:hover {
background-color: #eee;
}
```
JavaScript 代码:
```
// 获取所有的权限节点
var nodes = document.querySelectorAll('.tree .node');
// 遍历所有的节点,为其添加点击事件
nodes.forEach(function(node) {
node.addEventListener('click', function() {
var parent = this.parentNode;
var children = parent.querySelectorAll(':scope > ul');
children.forEach(function(child) {
child.classList.toggle('hidden');
});
});
});
```
这段代码主要实现了以下功能:
1. 使用 HTML 和 CSS 构建了一个基本的权限树状图。
2. 使用 JavaScript 获取所有的权限节点,并为其添加点击事件。
3. 点击节点时,展开或收起该节点下的子节点。