[英]How to highlight path from root to selected node in d3 js?
我用d3 js創建了一棵樹。 現在我創建了一個下拉菜單,其中包含樹中所有節點的列表。 現在,從下拉菜單中選擇一個節點,我想突出顯示從根到該特定節點的路徑。 這個怎么做?
首先制作一個展平函數,將分層數據轉換為數組。
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"
}
})
在這里工作代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.