仅在悬停时显示d3节点文本

use*_*009 16 mouseover nodes d3.js

我试图只在鼠标悬停时显示节点文本.当鼠标悬停在节点上时,我对svg圆圈的不透明度进行了更改,但只显示了第一个节点的文本.我已经发现这是因为我正在使用select元素,但我无法弄清楚如何为我正在悬停的节点提取正确的文本.这就是我现在拥有的.

node.append("svg:circle")
    .attr("r", function(d) { return radius_scale(parseInt(d.size)); })
    .attr("fill", function(d) { return d.fill; })
    .attr("stroke", function(d) { return d.stroke; })
    .on('mouseover', function(d){
        d3.select(this).style({opacity:'0.8'})
        d3.select("text").style({opacity:'1.0'});
                })
    .on('mouseout', function(d){
      d3.select(this).style({opacity:'0.0',})
      d3.select("text").style({opacity:'0.0'});
    })
    .call(force.drag);  
Run Code Online (Sandbox Code Playgroud)

Sco*_*ron 31

如果您使用d3.select,则在整个DOM中搜索<text>元素并选择第一个元素.要选择特定的文本节点,您需要更具体的选择器(例如#textnode1),或者需要使用子选择来约束特定父节点下的选择.例如,如果<text>元素直接位于示例中的节点下,则可以使用:

.on('mouseover', function(d){
    var nodeSelection = d3.select(this).style({opacity:'0.8'});
    nodeSelection.select("text").style({opacity:'1.0'});
})
Run Code Online (Sandbox Code Playgroud)