当鼠标悬停在由相同数据条目的不同属性创建的圆形元素时,我如何显示/隐藏文本元素?
D3 - How can I show/hide a text element when hovering a circle element created from different attributes of the same data entry?
我有一些数据有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/
相关文章:
- 在select元素中显示highchart dashstyle(svg)
- 限制ul元素中显示的项目
- x秒后在元素处显示气球
- 如何使用javascript在输入元素中显示特殊字符
- 仅在一个元素上显示微调器($.mobile.showPageLoadingMsg())
- JSON 元素未显示
- 为什么在Firebug中显示的元素没有显示在页面源代码中
- 删除的DOM元素仍然显示在移动safari(iOS 5.1)中
- 元素未显示在iOS表单提交中
- 将值发送到Javascript函数以在元素中显示
- 在隐藏元素中显示元素
- 每个元素仅显示可见元素
- 在JavaScript的HTML元素中显示console.log()
- 循环中元素的显示顺序
- 选取随机数组元素,将其移除,并在没有更多可用元素时显示消息
- 指令元素未显示
- HTML 转到另一个页面的特定元素(如果该元素尚未显示)
- 如何使用 Javascript 将鼠标悬停在元素上显示悬停
- 如果元素未显示在 Angular JS 中,则想隐藏“|”
- 元素后显示的所有元素的选择器