【发布时间】:2017-01-30 13:25:17
【问题描述】:
我使用以下实现了使用 HTML ul 和 li 的 JSON 模式的树结构。 JSFiddle
我希望在 HTML SVG 上实现同样的效果(因为以后会有可绘制的东西),我用 SVG:g 替换了 ul 和 li
有没有办法像 ul/li 一样向 g 中添加边框?我可以使用 SVG 线条来获得适当的结构,但有更好的方法吗?
var data = {
"title": "person",
"type": "object",
"properties": {
"first name": {
"type": "string"
},
"last name": {
"type": "string"
},
"age": {
"type": "number"
},
"birthday": {
"type": "string",
"format": "date-time"
},
"address": {
"type": "object",
"properties": {
"street address": {
"type": "object",
"properties": {
"house number": {
"type": "number"
},
"lane": {
"type": "string"
}
}
},
"city": {
"type": "string"
},
"state": {
"type": "string"
},
"country": {
"type": "string"
}
}
},
"phone number": {
"type": "array",
"items": {
"type": "object",
"properties": {
"location": {
"type": "string"
},
"code": {
"type": "number"
}
},
"required": [
"location",
"code"
]
}
},
"children": {
"type": "array",
"items": {
"type": "string"
}
},
"nickname": {
"type": "string"
}
}
};
var title = data.title || "Root";
var result1 = d3.select("#input-structure");
traverseJSONSchema1(data, title, result1 );
function traverseJSONSchema1(root, rootname, resultpane ) {
if (root.type === "object") {
var listitem = resultpane.append("li");
if (rootname !== "") {
listitem.text(rootname + ":" + root.type );
}
var newlist = listitem.append("ul");
var items = root.properties; //select PROPERTIES
for (var i = 0; i < Object.keys(items).length; i++) { //traverse through each PROPERTY of the object
var itemname = Object.keys(items)[i];
var item = items[itemname];
traverseJSONSchema1(item, itemname, newlist );
}
} else if (root.type === "array") {
var items = root.items; //select ITEMS
var listitem = resultpane.append("li");
if (rootname !== "") {
listitem.text(rootname + ":" + root.type + "[" + items.type + "]" );
}
traverseJSONSchema1(items, "", listitem ); //recurse through the items of array
} else if (["string", "integer", "number", "boolean"].indexOf(root.type) > -1) { //when the type is a primitive
var listitem = resultpane.append("li");
if (rootname !== "") {
listitem.text(rootname + ":" + root.type );
}
}
}
.structure,
.structure ul {
list-style-type: none;
text-indent: 5px;
}
li {
border-bottom: 1px solid #c9c9c9;
border-left: 1px solid #c9c9c9;
width: max-content;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div style="display:inline-block;">
<ul id="input-structure" class="structure">
</ul>
</div>
【问题讨论】:
-
不,你不能为 g 元素设置样式。
-
有没有办法找到 svg 组的边界?
标签: javascript html css d3.js svg