添加d3 svg.selectAll(".foo").style("fill",

Adding d3 svg.selectAll(".foo").style("fill",...) overrides .foo:hover css rule

本文关键字:quot style fill d3 svg 添加 selectAll foo      更新时间:2023-09-26

我正在制作一个d3 choropleth,它根据着色算法将初始fill属性值分配到:

  svg.selectAll(".foo")
      .style("fill", function(d){ 
        return colorization(getRandomArbitrary(5,25)); //returns hex value
      })

这工作。不幸的是,它似乎使我的CSS规则无关紧要。该规则在不通过d3调用.style()的情况下工作:

  .foo:hover{
    fill: white;
  }

我不确定这是d3.js正在做的事情,还是SVG样式和CSS样式之间某种相互作用的结果。

我正在寻找一个解决方案,完成算法着色,并继续允许:hover填充效果。

这是CSS的预期行为,并不是SVG或D3所独有的。内联样式覆盖:hover样式。您可以使用!important覆盖它。

.foo:hover {
    fill: white !important;
}

@Alexander O' mara的回答很好,然而,既然你说你是……寻找一个解决方案,完成算法着色…,我只是想让你注意到另一种不同的方法。

你可以显式地,编程地,设置悬停效果与这些行:

svg.selectAll(".foo")
    .style("fill", function(d){ 
        return colorization(getRandomArbitrary(5,25)); //returns hex value
    })
    .on("mouseover", function() { d3.select(this).style("fill", "white") } )
    .on("mouseout", function() { function(d){ 
        return colorization(getRandomArbitrary(5,25));
    })

这样你就不需要任何css文件-所以没有什么要"覆盖"的。:)

不幸的是,不能直接将":hover"样式从css转换为内联样式——必须使用事件处理程序,就像上面的代码一样!

灵感来自于这个问题的解决方案