如何突出显示d3 js中从根到所选节点的路径? [英] How to highlight path from root to selected node in d3 js?
本文介绍了如何突出显示d3 js中从根到所选节点的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经使用d3 js创建了一棵树.现在,我创建了一个下拉菜单,其中包含树中所有节点的列表.现在,从下拉菜单中选择一个节点,我想突出显示从根到该特定节点的路径.该怎么做?
I have created a tree using d3 js. Now i have created a drop-down menu containing list of all the nodes in the tree. Now on selecting a node from the drop down menu,i want to highlight path from root to that particular node. How to do this?
推荐答案
首先创建一个flatten函数,该函数将分层数据转换为n数组.
First make a flatten function which will make the hierarchical data into a n array.
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;
}
在选择框上添加如下所示的更改侦听器:
On the select box add a change listener like this:
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
});
在更新功能中,根据数据(在选择功能中设置)为路径着色,如下所示:
Inside your update function color the path according to the data (set in the select function) like this:
d3.selectAll("path").style("stroke", function(d) {
if (d.target.color) {
return d.target.color;//if the value is set
} else {
return "gray"
}
})
工作代码此处.
这篇关于如何突出显示d3 js中从根到所选节点的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文