当鼠标悬停在由相同数据条目的不同属性创建的圆形元素时,我如何显示/隐藏文本元素?

D3 - How can I show/hide a text element when hovering a circle element created from different attributes of the same data entry?

本文关键字:元素 何显示 显示 文本 隐藏 悬停 鼠标 数据 创建 属性      更新时间:2023-09-26

我有一些数据有2个属性:颜色和值

我使用D3输入选择来创建圆圈元素,并将它们附加到页面的主体。它们的填充颜色由" color "属性决定。

然后,向页面追加文本元素。文本内容由"value"属性决定。

下面是我正在处理的:

// Set up svg element
var svg = d3.select("body")
    .append("svg")
    .attr("width", 300)
    .attr("height", 300)
    .style("background", "lightblue");
var dataset = [
    {"colour":"red", "value":"First set of text"},
    {"colour":"green", "value":"Second attempt"},
    {"colour":"blue", "value":"Third and final!"}
];
// Create circles from the data
// On mouseover, give them a border (remove on mouseout)
svg.selectAll("circle")
    .data(dataset)
    .enter()
    .append("circle")
    .attr("r", 40)
    .attr("cy", function(d, i) { return i*80 + 40; })
    .attr("cx", 50)
    .style("fill", function(d) {return d.colour;})
  // HERE
  // Can I somehow show and hide the text component that is
  // associated with this circle when the circle is hovered, rather
  // than the text itself?
  .on("mouseover", function(d) {
          d3.select(this).style("stroke", "black")
                         .style("stroke-width", 2)
  })
  .on("mouseout", function(d) {d3.select(this).style("stroke", "none")});
// Now add the text for each circle
// Same thing with mouseover and mouseout
svg.selectAll("text")
    .data(dataset)
    .enter()
    .append("text")
    .attr("text-anchor", "middle")
    .attr("y", function(d, i) { return i*80 + 40; })
    .attr("x", 50)
    .style("opacity", 0)
    .on("mouseover", function(d) {d3.select(this).style("opacity", 1)})
    .on("mouseout", function(d) {d3.select(this).style("opacity", 0)})
    .text(function(d) { return d.value;});

我想为文本隐藏,直到相关的圆圈被悬停在上面。如何将文本元素与特定的圆圈连接起来,以便通过将鼠标悬停在圆圈上来切换文本是否显示?

下面的小提琴是我正在尝试做的事情的大纲,以及我到目前为止所得到的。我让文本只在悬停时显示,而不是在圆圈悬停时显示。

https://jsfiddle.net/aj4zpn6z/

有几种方法可以实现这一点。由于圆圈和文本都使用相同的数据集,因此我的解决方案使用filter

首先,让我们命名文本和圆圈的变量:

var circles = svg.selectAll("circle")
    //etc...
var texts = svg.selectAll("text")
    //etc...

然后,在圆圈mouseover函数中,我们过滤具有相同colour属性的文本:

.on("mouseover", function(d){
    d3.select(this).style("stroke", "black").style("stroke-width", 2);
    var tempTexts = texts.filter(function(e){
        return e.colour === d.colour
    });
    tempTexts.style("opacity", 1);
});

这是您的更新小提琴:https://jsfiddle.net/wxh95e9u/