我有一个条形图,我想在单击条形图时更改颜色。我想在单击的元素上设置 CSS 类。一切正常,除了填充样式(单击的栏的颜色)没有改变,但应用了绿色描边。我不明白为什么。
这是单击图表最后一个柱之前和之后的屏幕
这就是我想要实现的目标
这是我的代码的一部分,有什么建议吗?
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;
}
不负相思意
相关分类