定义 D3 样式 SVG 元素

D3 styling SVG elements when defined

本文关键字:元素 SVG 样式 D3 定义      更新时间:2023-09-26

我有一个带有轴的 D3 图表,我想通过原始调用来设置样式来创建它。但是,它似乎只在第一次调用时起作用。我会告诉你我的意思:

当我通过以下方式创建轴时

svg.select('g.y.axis').call(yaxis)
    .selectAll("path")
        .attr("fill","none")
      .attr("stroke", "#000")
    .selectAll("line")
        .attr("fill","none")
      .attr("stroke", "#000");

只有路径的样式正确。你可以看看我的jsfiddle,看看我的意思。我知道这可能比仅仅使用 CSS 样式慢,但我需要在我正在处理的原始调用中设置样式。提前感谢!

这是因为d3.selectAll("foo").selectAll("bar")会尝试找到<bar> s,这些元素是建立<foo> s的内部元素。在您的情况下,svg 在 <path> s 中找不到<line>

只需单独致电:

svg.selectAll("path")...
svg.selectAll("line")...

UPD要在 .y.axis 中查找路径/线:

svg.select(".y.axis").selectAll("path")

svg.selectAll(".y.axis path")