使用 JavaScript 构建一个组织架构树节点
Posted 张驰Terry
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用 JavaScript 构建一个组织架构树节点相关的知识,希望对你有一定的参考价值。
Demo
https://jsfiddle.net/me7jb6f8/
Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>organizationTree</title>
<style>
*
box-sizing: border-box;
padding: 0;
margin: 0;
.box
position: absolute;
width: 9999px;
height: 9999px;
overflow: auto;
top: 300px;
.box-item
width: 80px;
height: 30px;
border: 1px solid #ccc;
position: absolute;
text-align: center;
border-radius: 10px;
</style>
</head>
<body>
<div id="box" class="box"></div>
<script>
const box_el = document.getElementById("box");
const TREE_NODE_RECT =
width: 80,
height: 30,
margin: 30,
;
const get_px = function(str)
return Number(str.replace('px',''))
function addChild(parent_el, current_depth, depth)
if(current_depth>=depth)
return;
const is_root = current_depth === 0;
const children_count = is_root?1:2;
for (let i = 0; i < children_count; i++)
let child_el = document.createElement("div");
child_el.className = "box-item";
if(parent_el)
child_el.style.left = get_px(parent_el.style.left) -TREE_NODE_RECT.width * (Math.pow(2,depth-current_depth-1))*(i===0?-1:1) + "px";
child_el.style.top = get_px(parent_el.style.top) + TREE_NODE_RECT.margin * current_depth + "px";
child_el.innerHTML = parent_el.innerHTML+'_'+ i;
else
child_el.style.left = TREE_NODE_RECT.width *Math.pow(2,depth)+'px';;
child_el.innerHTML = '0';
box_el.appendChild(child_el);
addChild(child_el, current_depth+1, depth);
function createTree(depth)
addChild(null, 0, depth);
createTree(5);
</script>
</body>
</html>
以上是关于使用 JavaScript 构建一个组织架构树节点的主要内容,如果未能解决你的问题,请参考以下文章