覆盖 CSS 会导致 D3JS 树路径 link 在节点展开或折叠后可见

Overriding the CSS causes D3JS tree path link to be visible after node expansion or collapse

我的代码类似于 this plunkr 中的示例。 我正在尝试覆盖 CSS 中的“.link”条目以下载为 SVG 文档。

.link {fill: none; stroke: #ccc; stroke-width: 1.5px;}

问题是,一旦我这样做,link 不会在节点扩展或折叠时被删除。

我把原代码中的class属性注释掉,在下面的函数中插入属性:

// Update the linksâ¦
var link = svg.selectAll("path.link")
   .data(links, function (d) {
      return d.target.id;
});

// Enter any new links at the parent's previous position.
link.enter().append("path", "g")
   //.attr("class", "link")
   .attr("stroke", "#ccc")
   .attr("fill", "none")
   .attr("stroke-width", "2px")
   .attr("x", boxWidth )
   .attr("y", boxHeight)
   .attr("d", function (d) {
     console.log(source)
   var o = {
       x: source.x0,
       y: source.y0
   };
   return diagonal({
       source: o,
       target: o
   });

});

是否了解为什么会出现这种行为?

您的原密码是:

var link = svg.selectAll("path.link")
  ...

link.enter()
  .append("path")
  .attr("class","link")
  ...

如果删除附加项的 class,那么每次绘制树时,第一个选择 (link) 将为空(因为没有带有 [=26= 的路径) ] link)。因此,将输入数据数组中的任何 link。这就是代码最初按预期工作的原因。但是,link 永远不会更新或退出,因为选择中没有要更新或退出的元素 - 选择将始终为空。

如果这些是您唯一的路径,您可以将选择器更改为:

 var link = svg.selectAll("path")
   ...

Eg.

或者,您可以保留与元素关联的 class,但删除与 class 关联的任何 css 样式。在任何一种情况下,您都可以使用 .attr() 应用样式属性,就像您所做的那样。