我有一个D3条形图,相关的数据点显示为每个条形顶部的文本 . 我想仅在鼠标悬停时显示文本,并使栏具有不同的填充颜色 . 因此,基本上,在鼠标悬停时,条形图必须设置为具有不同的填充颜色,文本不透明度应为1(从“0”开始) .
我无法在鼠标悬停上影响两个单独的事件 . 我已经为这两个元素赋予了一个index_value属性,以便使用d3.select(this).attr(index_value) . 但我的鼠标悬停功能不起作用 . 我不知道为什么 . 这是我的相关代码部分 .
条形图
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr('data-value', function(d){return d[region]})
.attr("x", function(d) { return x(d.year); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d[region]); })
.attr("height", function(d) { return height - y(d[region]); })
.attr("fill", color)
.attr("index_year", function(d, i) { return "index-" + d.year; })
.attr("class", function(d){return "bar " + "bar-index-" + d.year;})
.attr("color_value", color)
.on('mouseover', synchronizedMouseOver)
.on("mouseout", synchronizedMouseOut);
文字叠加
svg.selectAll(".bartext")
.data(data)
.enter()
.append("text")
.attr("text-anchor", "middle")
.attr("x", function(d,i) {
return x(d.year)+x.rangeBand()/2;
})
.attr("y", function(d,i) {
return height - (height - y(d[region])) - yTextPadding;
})
.text(function(d){
return d3.format(prefix)(d3.round(d[region]));
})
.attr("index_year", function(d, i) { return "index-" + d.year; })
.attr("class", function(d){return "bartext " + "label-index-" + d.year;})
.on("mouseover", synchronizedMouseOver)
.on("mouseout", synchronizedMouseOut);
和鼠标悬停功能
var synchronizedMouseOver = function() {
var bar = d3.select(this);
console.log(bar);
var indexValue = bar.attr("index_year");
var barSelector = "." + "bar " + "bar-" + indexValue;
var selectedBar = d3.selectAll(barSelector);
selectedBar.style("fill", "#f7fcb9");
var labelSelector = "." + "bartext " + "label-" + indexValue;
var selectedLabel = d3.selectAll(labelSelector);
selectedLabel.style("opacity", "1");
};
1 回答
这可以通过简化您的听众来实现 . 您不需要为rects和text添加侦听器 . 只需将它们添加到rects中即可 . 以下是简化的听众:
这里你的两个朋友分别是
this
和d
,这是DOM及其数据节点的DOM元素 .这是一个FIDDLE,你想要的行为 .