我使用d3 js创建了一棵树。现在我创建了一个下拉菜单,其中包含树中所有节点的列表。现在,从下拉菜单中选择一个节点,我想突出显示从根到该特定节点的路径。怎么做?
答案 0 :(得分:1)
首先制作一个展平函数,将分层数据转换为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
});
在更新功能中,根据数据(在select函数中设置)对路径进行着色,如下所示:
d3.selectAll("path").style("stroke", function(d) {
if (d.target.color) {
return d.target.color;//if the value is set
} else {
return "gray"
}
})
工作代码here。