简体   繁体   English

如何在d3 js中突出显示从根到选定节点的路径?

[英]How to highlight path from root to selected node in d3 js?

I have created a tree using d3 js. 我用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? 这个怎么做?

First make a flatten function which will make the hierarchical data into an 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: 在更新函数内部根据数据(在select函数中设置)颜色路径,如下所示:

d3.selectAll("path").style("stroke", function(d) {
          if (d.target.color) {
            return d.target.color;//if the value is set
          } else {
            return "gray"
          }
        })

Working code here . 在这里工作代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM