D3-当悬停从同一数据条目的不同属性创建的圆形元素时,如何显示/隐藏文本元素?

新川91

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

我使用D3 enter选择创建圆形元素,并将其附加到页面正文中。它们的填充颜色由“颜色”属性确定。

然后,我将文本元素附加到页面。文本内容由“值”属性确定。

这是我正在处理的内容:

// 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/

杰拉尔多·富塔多(Gerardo Furtado)

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

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

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

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

然后,在circlemouseover函数中,我们过滤具有相同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/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章