【问题标题】:How to select elements according to an attribute(fill color) in D3.js with SelectAll如何使用 SelectAll 在 D3.js 中根据属性(填充颜色)选择元素
【发布时间】:2014-09-07 14:12:35
【问题描述】:

我在地图上有一组圆圈,例如 10 个红色圆圈、10 个蓝色圆圈、10 个绿色圆圈。如何使用 d3 selectAll 或 select 仅选择红色圆圈?

或者还有其他方法吗?

颜色是这样给出的(作为“样式”属性中“填充”的值,

feature = g.selectAll("circle")
    .data(data)
    .enter().append("circle")
    .attr("id", function (d) {
    return d.ArtistID + d.FollowerID;
})
    .style("stroke", "black")
    .style("opacity", .6)
    .style("fill", function (d) {
    if (d.ArtistID == 1) {
        return "red"
    } else if (d.ArtistID == 2) {
        return "blue"
    } else {
        return "green"
    };
})
    .attr("r", 10);

所以,圆圈会画成这样,

<circle id="10" r="10" transform="translate(695,236)" style="stroke: rgb(0, 0, 0); opacity: 0.6; fill: rgb(255, 255, 0);"></circle>

我想选择红色的圆圈。有人帮忙吗?

提前致谢。

【问题讨论】:

标签: javascript css d3.js


【解决方案1】:

您要求根据style 属性的值进行选择。 fill 属性嵌套在 style 属性中;它不是 DOM 节点的直接属性。因此,您将无法使用属性选择器(即链接到的 @LarsKotthoff 方法)来选择它。

您可以切换到使用 SVG fill 属性 .attr('fill', ...) 来设置填充,而不是使用 style('fill'),这将允许您稍后使用属性选择器来选择它。

除此之外,通过填充属性进行选择似乎不太优雅。如果您的设计不断发展并且您开始使用不同的填充颜色,则您还必须更改属性选择器。给它分配一个类并根据类进行选择更合适。

也许最好是根据数据进行选择。例如:

g.selectAll('circle')
  .filter(function(d) { return d.ArtistID == 1; })
  .style('fill', function(d, i) {
    // here you can affect just the red circles (bc their ArtistID is 1)
  })

【讨论】:

    猜你喜欢
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多