使用d3js力导向图更新特定节点的样式。

4

如何最简单地更新已经绘制的节点的样式?在这种情况下,布局已经创建完成,所有的链接、节点都是完美的。然后,将一个数组传递给指令,如果节点名称在该数组中,我想更改它的颜色。

例如:

var names = ["tom","john"]; // this data comes in...


                d3.select("node").select("circle").style("fill", function (d) {
                   // I check if the node name is in array, if so change its colour to green.
                    if (names.indexOf(d.name) > -1) {
                        return "green";
                    } else
                        return "red";

                });
2个回答

2

尝试使用filter进行选择

d3.selectAll("node").selectAll("circle")
  .filter(function(d){
    return names.indexOf(d.name) < 0;
  })
  .style("fill", "red");

0

ahmohamed的方法很好。另一个选择:在构建页面时,将名称作为每个节点的id值或附加的class添加。然后,您可以使用该id或class选择要选择的元素,可能使用复合CSS选择器。例如,如果您将名称设置为id,则可以执行以下操作:

d3.selectAll("node").selectAll("#tom").style("fill", "green");

这里的“#tom”指的是所有具有 id ="tom"的DOM元素。 如果除了带有“tom”作为id的圆形之外还有其他东西,那么这应该可以工作:
d3.selectAll("node").selectAll("circle#tom").style("fill", "green");

这段代码的意思是获取所有 id="tom"circle 元素。

(也许可以使用选择器中的某种 OR 运算符来组合 #tom#john。但我不确定。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接