【问题标题】:D3.js Highlight an element when hovering over anotherD3.js 悬停在另一个元素上时突出显示一个元素
【发布时间】:2016-11-10 13:06:40
【问题描述】:

我有一个使用 D3.js 制作的圆环图。当鼠标悬停在相应的文字上时,我想改变弧线的颜色。

我知道如何更改第一个或全部的颜色,但相应的一个。

Here 是目前为止的代码。突出显示的行如下:

           .on("mouseover", function(d,i){
              //d3.select(".donutArcSlices").transition().style("fill", "#007DBC");
              //d3.selectAll(".donutArcSlices").transition().style("fill", "#007DBC");
              div.transition()      
                .duration(200)      
                .style("opacity", .9);      
            div .html(d.name)   
                .style("left", (d3.event.pageX) + "px")     
                .style("top", (d3.event.pageY - 28) + "px");
            })
            .on("mouseout", function(d) {       
              d3.select(".donutArcSlices").transition().style("fill", "#3E4750");
              div.transition()      
                .duration(500)      
                .style("opacity", 0);   
            });

如果我添加第一条注释行,当我将鼠标悬停在弧线中的任何文本上时,第一条弧线会改变颜色。如果我删除第二行的 cmets,那么所有的弧线都会在悬停在任何文本上时改变颜色。

【问题讨论】:

  • 两个答案都很好,我会让社区决定哪个答案应该被接受。

标签: javascript d3.js hover


【解决方案1】:

给每条路径一个唯一的ID:

.attr("id", function(d,i){ return "donut"+i})

悬停时使用:

d3.select("#donut" + i).transition().style("fill", "#007DBC");

这是你的小提琴:https://jsfiddle.net/d6839s03/

PS:你的mouseout 函数让一切都变灰了。

【讨论】:

  • 是的,mouseout 没有完全实现,因为它使用了相同的功能。
【解决方案2】:

您可以像这样过滤正确的路径:

d3.selectAll(".donutArcSlices").filter(function(e, j){ return i === j}).style("fill", "#007DBC");

https://jsfiddle.net/o98b8fsj/

【讨论】:

    【解决方案3】:

    Gerardo 的绝妙答案。任何尝试使用 D3js v5 的人都可以使用相同的基本概念。 我正在使用带有以下代码 sn-ps-

    的 D3js V5 + Angular 6
    1. 将 id 属性添加到节点或您要操作的任何其他元素 -

      this.svg.append('g').attr('id' ,(d,i)=>'elementname'+i)

    2. 然后只需对您选择的 d3js 事件进行更改 -

      .on('mousehover', (d,i)=> d3.select('#elementname'+i).style('fill','red') .on('mouseout', (d,i)=> d3.select('#elementname'+i).style('fill','black')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      相关资源
      最近更新 更多