我用 D3.js 绘制了一个水平条形图。每个条形都有一个标签,并且条形在鼠标悬停时会改变颜色。标签可见性最初设置为隐藏。
var bars = gw2.selectAll(".bar")
.data(data)
.enter()
.append("g")
//append rects
bars.append("rect")
.attr("class", "bar")
.attr("id", function(d) { return d.country+"_bar"; })
.attr("y", function(d) { return y2(d.country); })
.attr("height", y2.bandwidth())
.style("filter", "url(#drop-shadow-h)")
.attr("width", function(d) { return x2(d.value); });
//add a value label to the right of each bar
bars.append("text")
.attr("class", "textlbl")
.attr("id", function(d) { return d.country+"_lbl"; })
.attr("fill", "#404040")
.attr("x", function(d) { return x2(d.value) - 5 })
.attr("y", function(d){ return y2(d.country) + (y2.bandwidth()/2); })
.attr("dy", ".35em") //vertical align middle
.style("text-anchor", "end")
.text(function(d){ return (d.value); });
.textlbl {
font-size: 0.7rem;
font-weight: bold;
visibility: hidden;
}
我希望,除了鼠标悬停上单条的颜色变化外,相应的标签也会将可见性更改为“可见”。单条如下:
<g>
<rect class="bar" id="Greece_bar" y="149" height="14" width="230" style="filter: url("#drop-shadow-h");"></rect>
<text class="textlbl" id="Greece_lbl" fill="#404040" x="225" y="156" dy=".35em" style="text-anchor: end; visibility: hidden;">56.6</text>
</g>
我尝试了不同的解决方案,但它们不起作用。首先,使用“selectAll”,但它选择所有条形和所有标签,而不仅仅是鼠标悬停的那个:
gw2.selectAll(".bar")
.on("mouseover", function(d){
d3.selectAll(".textlbl").style("visibility", "visible");
});
然后我尝试了 'this',但我无法获得选择器 'textlbl' 并且代码返回错误“'[object SVGRectElement]+.textlbl' is not a valid selector”。
gw2.select(".bar")
.on("mouseover", function(d){
d3.select(this+"+.textlbl").style("visibility", "visible");
});
有什么建议吗?
也许这会做。
在d3中你不能选择兄弟姐妹,先去父母
gw2.select(".bar")
.on("mouseover", function(d){
d3.select(this.parentNode).select('.textlbl').style("visibility", "visible");
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句