我使用 d3 js 创建了一棵树。现在我创建了一个下拉菜单,其中包含树中所有节点的列表。现在,从下拉菜单中选择一个节点时,我想突出显示从根到该特定节点的路径。这个怎么做?
首先创建一个 flatten 函数,它将分层数据变成一个 n 数组。
function flatten(root) {
var nodes = [],
i = 0;
function recurse(node) {
if (node.children) node.children.forEach(recurse);
if (node._children) node._children.forEach(recurse);
if (!node.id) node.id = ++i;
nodes.push(node);
}
recurse(root);
return nodes;
}
在选择框中添加一个更改侦听器,如下所示:
var select = d3.select("body")
.append("select")
.on("change", function() {
//get the value of the select
var select = d3.select("select").node().value;
//find selected data from flattened root record
var find = flatten(root).find(function(d) {
if (d.name == select)
return true;
});
//reset all the data to have color undefined.
flatten(root).forEach(function(d) {
d.color = undefined;
})
//iterate over the selected node and set color as red.
//till it reaches it reaches the root
while (find.parent) {
find.color = "red";
find = find.parent;
}
update(find);//call update to reflect the color change
});
在更新函数内,根据数据(在选择函数中设置)为路径着色,如下所示:
d3.selectAll("path").style("stroke", function(d) {
if (d.target.color) {
return d.target.color;//if the value is set
} else {
return "gray"
}
})
工作代码here http://plnkr.co/edit/SKVV4A7a9bV0bZupS9M2?p=preview.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)