【问题标题】:darken rect/circle on mouseover in d3在d3中鼠标悬停时使矩形/圆形变暗
【发布时间】:2013-11-28 22:29:55
【问题描述】:

我正在使用 d3 绘制几个填充有特定颜色的矩形和圆形。

现在,将鼠标指针悬停在我的对象上时,它们会变暗。我的想法是通过在围绕每个对象的 g 标签上放置一个带有 alpha 的黑色背景来使用 CSS:

g:hover {
  background-color: rgba(0, 0, 0, .5);
}

但这不起作用。当我将opacity: .5 放在那里时,它确实有效,但我希望它更暗,而不是更亮。有人有什么提示吗? 谢谢!

【问题讨论】:

  • 你能发布所有代码吗?还是做个小提琴?

标签: css svg d3.js


【解决方案1】:

我认为您不能可靠地在 SVG 元素上使用悬停伪。而是使用 d3 在 mouseover 时添加一个类,并在 mouseout 时将其删除。

例如:

svg.append("g")
    .on("mouseover", function() {
        d3.select(this).classed("hover", true);
      })
    .on("mouseout", function() {
         d3.select(this).classed("hover", false);
    })

然后在 CSS 中

g.hover {
    background-color: rgba(0, 0, 0, .5);
}

希望对您有所帮助。

编辑:也许你可以使用 :hover。看这个问答https://stackoverflow.com/a/9210392/2594702

基本上它说使用fill: rgba(0, 0, 0, .5) 而不是background-color

我确定我记得我在学习 D3 以使用鼠标悬停和鼠标悬停时阅读过。也许当时浏览器支持不如现在好。

【讨论】:

  • 是的,:hover 可以正常工作,但在background-colorfill 上都没有rgba()
【解决方案2】:

:hover 东西通常可以工作,但是将它应用到作为矩形的父级而不是覆盖子级的 g 标记上是错误的方法。

我现在通过将mouseover 事件添加到rect 标记来解决整个问题,读出fill 属性的颜色值并计算出一个更暗的值。可能不是最好的解决方案,但我没有其他想法,但它确实有效。

.on("mouseover", function() {
    if((r = $(this).css("fill").match(/(\d+),\s*(\d+),\s*(\d+)/i))) {
        for(var i = 1; i < 4; i++) {
            r[i] = Math.round(r[i] * .5);
        }
        $(this).attr("fill-old", $(this).css("fill"));
        $(this).css("fill", 'rgb('+r[1]+','+r[2]+','+r[3]+')');
    }
})
.on("mouseout", function() {
    if($(this).attr("fill-old")) $(this).css("fill", $(this).attr("fill-old"));
});

【讨论】:

    【解决方案3】:

    适用于 D3 版本。 4 在我的甜甜圈图上,我遇到了同样的问题。我找到了mboostocks 解决方案,可以在here 找到。我以他的第二个例子为例,将“更亮”替换为“更暗”。我的结果代码:

    .on("mouseover", function(d){
        d3.select(this).style("fill", function() {
            return d3.rgb(d3.select(this).style("fill")).darker(0.2);
        });
    });
    

    【讨论】:

      【解决方案4】:

      在现代浏览器中,您可以使用 CSS 亮度函数来使颜色变亮/变暗。

      .on('mouseover', (event, d) => {
          d3.select(event.target)
             .style('filter', 'brightness(50%)')
          })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 2021-12-20
        • 1970-01-01
        • 2011-11-09
        • 1970-01-01
        • 2012-05-10
        相关资源
        最近更新 更多