D3 color change on mouseover using classed(“active”,true)

别等时光非礼了梦想. 提交于 2019-12-04 08:19:38

EDIT

First off, you were right that your CSS is slightly off.

.tile active {
  fill: red;
}

should be:

.tile.active {
  fill: red;
}

Then, sort of like I explained below, the fill you're applying to the element with

.style("fill", function(d) { return z(d.count_shipments); })

ends up taking precedence over the fill applied by the active class.

However, unlike what I initially suggested, you can work around it by simply swapping style with attr, so you need:

.attr("fill", function(d) { return z(d.count_shipments); })

(probably should do this for stroke as well).

Here's an updated, working jsFiddle


ORIGINAL POST

I suspect it works the way it should –– i.e. class "active" with its associated fill is being added/removed appropriately –– and you'd be able to verify this by right-clicking and inspecting the element in dev tools.

I think the real problem is that you're also setting a fill directly on the element (one line before your .on("mouseover"...) call), which ALWAYS overrides the fill applied by your class. Generally in CSS you could (not saying you should) use the !important keyword to force it to accept the fill applied by the class. But I'm pretty sure that won't work with SVG (as opposed to normal HTML elements).

So, I think your only option is:

.style("fill", function(d) { return z(d.count_shipments); })
.on("mouseover", function() {
  d3.select(this)
    .attr('fill', '') // Un-sets the "explicit" fill (might need to be null instead of '')
    .classed("active", true ) // should then accept fill from CSS
})
.on("mouseout",  function() {
  d3.select(this)
    .classed("active", false)
    .attr('fill', function(d) { return z(d.count_shipments); }) // Re-sets the "explicit" fill
  });

Hope this works....

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!