为了账号安全,请及时绑定邮箱和手机立即绑定

更改类时不应用 D3 css

更改类时不应用 D3 css

Helenr 2023-09-07 16:10:39
我有一个条形图,我想在单击条形图时更改颜色。我想在单击的元素上设置 CSS 类。一切正常,除了填充样式(单击的栏的颜色)没有改变,但应用了绿色描边。我不明白为什么。这是单击图表最后一个柱之前和之后的屏幕 这就是我想要实现的目标这是我的代码的一部分,有什么建议吗?JS//CREATE THE BAR CHARTvar bars = d3  .select("#bars")  .selectAll("rect")  .data(data);bars  .enter()  .append("rect")  .attr("x", function(d) {    return xScale(d.year);  })  .attr("y", function(d) {    return yScale(d.cost);  })  .attr("width", xScale.bandwidth)  .attr("height", function(d) {    return height - yScale(d.cost);  })  .style("fill", function(d) {    return colorScale(d.cost);  });//EVENT ON CLICKd3.select("#bars")  .selectAll("rect")  .on("click", function() {    //reset the previus bar selected    d3.select("#bars")      .select(".selected")      .classed("selected", false)      .style("fill", function(d) {        return colorScale(d.cost);  //reset the original color      });    //set the current bar as selected    d3.select(this).classed("selected", true);  });CSS.selected {  fill: red;  stroke: green;  stroke-width: 3;}
查看完整描述

1 回答

?
不负相思意

TA贡献1777条经验 获得超10个赞

一般来说,属性样式会被使用选择器的 CSS 样式覆盖,而 CSS 样式又会被内联 CSS 样式覆盖。

  • .attr("fill", "blue")设置属性fill="blue"

  • .selected { fill: "red"; }应用风格fill: red;

  • .style("fill", "green")设置属性style="fill: green;",内联样式。

如果将所有这些应用于同一元素,则最后一个优先。通过取消选择先前选择的栏,您可以赋予它.style("fill",从而覆盖任何潜在的未来样式。我建议检查您是否真的需要应用这些样式,.attr()如果需要就使用。

我在下面添加了一个小展示柜。

let settings = {

  attr: false,

  class: false,

  style: false,

};

draw();


function draw() {

  d3.select("rect")

    .attr("fill", settings.attr ? "red" : null)

    .attr("class", settings.class ? "blue" : "")

    .style("fill", settings.style ? "green" : null);

}


d3.selectAll("[type='checkbox']")

  .on("change", function() {

    settings[this.getAttribute("id")] = this.checked;

    draw();

  });

.blue {

  fill: blue;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<div>

  <input type="checkbox" id="attr"/><label for="attr">attr</label>

  <input type="checkbox" id="class"/><label for="class">class</label>

  <input type="checkbox" id="style"/><label for="style">style</label>

</div>

<svg>

  <rect width="30" height="30"></rect>

</svg>


查看完整回答
反对 回复 2023-09-07
  • 1 回答
  • 0 关注
  • 53 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信