猿问

更改类时不应用 D3 css

我有一个条形图,我想在单击条形图时更改颜色。我想在单击的元素上设置 CSS 类。一切正常,除了填充样式(单击的栏的颜色)没有改变,但应用了绿色描边。我不明白为什么。

这是单击图表最后一个柱之前和之后的屏幕 

这就是我想要实现的目标

https://img4.mukewang.com/64f986df0001c33c11690358.jpg

这是我的代码的一部分,有什么建议吗?


JS


//CREATE THE BAR CHART

var 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 CLICK

d3.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;

}

Helenr
浏览 93回答 1
1回答

不负相思意

一般来说,属性样式会被使用选择器的 CSS 样式覆盖,而 CSS 样式又会被内联 CSS 样式覆盖。.attr("fill", "blue")设置属性fill="blue";.selected { fill: "red"; }应用风格fill: red;;.style("fill", "green")设置属性style="fill: green;",内联样式。如果将所有这些应用于同一元素,则最后一个优先。通过取消选择先前选择的栏,您可以赋予它.style("fill",从而覆盖任何潜在的未来样式。我建议检查您是否真的需要应用这些样式,.attr()如果需要就使用。我在下面添加了一个小展示柜。let settings = {&nbsp; attr: false,&nbsp; class: false,&nbsp; style: false,};draw();function draw() {&nbsp; d3.select("rect")&nbsp; &nbsp; .attr("fill", settings.attr ? "red" : null)&nbsp; &nbsp; .attr("class", settings.class ? "blue" : "")&nbsp; &nbsp; .style("fill", settings.style ? "green" : null);}d3.selectAll("[type='checkbox']")&nbsp; .on("change", function() {&nbsp; &nbsp; settings[this.getAttribute("id")] = this.checked;&nbsp; &nbsp; draw();&nbsp; });.blue {&nbsp; fill: blue;}<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script><div>&nbsp; <input type="checkbox" id="attr"/><label for="attr">attr</label>&nbsp; <input type="checkbox" id="class"/><label for="class">class</label>&nbsp; <input type="checkbox" id="style"/><label for="style">style</label></div><svg>&nbsp; <rect width="30" height="30"></rect></svg>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答