【问题标题】:Highlight parent path to the root突出显示根的父路径
【发布时间】:2018-06-25 06:23:40
【问题描述】:

我尝试通过更改节点和链接的填充来突出显示从鼠标指向根节点的节点的路径。我在 Block 上使用 Mike's 的 Radial Tidy Tree。

我尝试了node.ancestors(),但这未被识别为函数。 当我尝试创建一个变量并将node.parent 放入其中或使用d3.select(this.parentNode) 时,它也不起作用。

我在 Google 网上论坛上发现有人试图反其道而行之,而 Mike Bostock told them 问题出在他的树数据上。

我使用了 Mike 给出的方法,效果很好:

node.on("mouseover", function(p) {

  //color the links
  link.filter(function(d) {
    for (d = d.source; d; d = d.parent) {
      if (d === p) return true;

      }
  }).style("stroke","black");

  //color the nodes 
  node.filter(function(d) {
    while(d = d.parent){
      if(d === p) return true ;
    }
  }).style("fill","red");

});

它改变了颜色,我也对mouseout做了相反的事情。 但是我不能用相反的方向配置它(节点到父级到根),有人可以帮我做吗?

【问题讨论】:

    标签: javascript d3.js path tree highlight


    【解决方案1】:

    为了完整性:ancestors()工作,但你必须在层次结构上调用它,而不是在选择上:

    .on("mouseover", function(d) {
        var filtered = node.filter(function(e) {
            return d.ancestors().indexOf(e) > -1
        });
        filtered.selectAll("circle").style("fill", "red");
        filtered.selectAll("text").style("fill", "red");
    })
    

    这里是更新的 bl.ocks:https://bl.ocks.org/anonymous/bb5be85d509eb7824e95d193c4fb6d27/e87fb16f8058f85719647dde561bff12f998361a

    【讨论】:

      【解决方案2】:

      您需要一种稍微不同的方法来让节点从子节点转到根节点。想到的一个选项是收集链中所有节点的列表:

      node.on("mouseover", function(p) {
      
          var nodes = [];
          nodes.push(p);
      
          while(p.parent) {
              p = p.parent;
              nodes.push(p);
          }
      

      由于每个具有父节点的节点都有一个包含其父对象的属性,因此这将为您获取所选节点上游的每个节点。鼠标悬停的节点也被选中,这将允许我们选择链接。

      现在要设置节点的样式很容易,只需查看节点的基准是否位于我们刚刚创建的节点数组中:

        node.filter(function(d) {
              if(nodes.indexOf(d) !== -1) return true;
        }).style("fill","steelblue");
      

      为了给节点着色,我们使用类似的方法,但检查每个链接的目标是否在我们的节点数组中:

        //color the links
        link.filter(function(d) {
           if(nodes.indexOf(d.target) !== -1) return true;
        }).style("stroke","orange");
      

      必须是目标 - 因为每个节点只有一条路径会终止,但每个节点可能会出现多条路径,这就是为什么我们需要将原始节点的数据推入数组中

      Here's 设置只有上游突出显示。

      【讨论】:

        猜你喜欢
        • 2018-09-10
        • 2013-11-03
        • 2018-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-09
        • 2018-10-12
        相关资源
        最近更新 更多