Div与SVG的Javascript树映射



我需要一个类似plotly的树图:https://plotly.com/python/treemaps/对于反应应用,它支持缩放功能,因此可以探索多个层,而不需要同时显示所有层。我不能使用情节,因为它似乎违反了CSP,我找不到任何其他库,有一个对我有用的例子。

我知道应该考虑编写一个自定义的树图组件。我尝试过的每一个树图都是用SVG构建的。然而,我对SVG没有任何经验,更喜欢使用div元素构建树图。由于我找不到任何使用div元素的解决方案,我想知道是否存在我不知道的陷阱。

我知道DOM元素太多可能是个问题。但我不需要一次显示超过2层,这永远不会超过200个元素。

这个例子是可以以树的形式出现的东西的开始。它是用基于对象data的div制作的。

我开始设计它的风格,但它需要一些实验和结构。。。

const data = {
'1': {
'1.1': {
'1.1.1': {}
},
'1.2': {}
},
'2': {
'2.1': {},
'2.2': {
'2.2.1': {},
'2.2.2': {}
}
}
};
const tree = document.getElementById('tree');
const insertchildren = (parent, obj, level) => {
Object.keys(obj).forEach(key => {
let child = document.createElement('div');
child.setAttribute('class', `node v${Object.keys(obj[key]).length} l${level}`);
let title = document.createElement('div');
title.setAttribute('class', 'title');
title.textContent = key;
child.appendChild(title);
parent.appendChild(child);
insertchildren(child, obj[key], level + 1);
});
};
insertchildren(tree, data, 1);
div#tree {
display: flex;
flex-direction: row;
}
.l1 {
flex-direction: column;
}
.l2 {
flex-direction: row;
}
.l3 {
flex-direction: column;
}
div.node {
display: flex;
padding: 2px;
border: solid thin black;
margin: 2px;
box-sizing: border-box;
}
.title {
width: 100%;
}
.v0 {
height: 100px;
}
<div id="tree" class="v2"></div>

最新更新