当一个元素悬停在另一个元素上时高亮显示

D3.js Highlight an element when hovering over another

本文关键字:元素 另一个 高亮 显示 悬停 一个      更新时间:2023-09-26

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

我知道如何改变第一个或所有的颜色,但对应的一个。

下面是到目前为止的代码。做高亮显示的行如下:
           .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);   
            });

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

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

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

并在悬停时使用:

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

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

PS:你的mouseout函数是使一切灰色。

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

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

见https://jsfiddle.net/o98b8fsj/

Gerardo的回答真棒。任何尝试使用D3js v5的人都可以使用相同的底层概念。我使用的是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')