在 D3 4.0 中,callback function for the .on() method is passed 3 arguments:当前数据 (d)、当前索引 (i) 和当前组(节点)。
在鼠标悬停回调中,您可以selectAll("rect"),并过滤掉当前组(node)中的项目。使用此选择,然后将不透明度设置为 0.5。在 mouseout 上,您只需将所有不透明度设置回 1.0。相关代码为:
...
.on('mouseover', function(d, i, node) {
d3.selectAll("rect")
.filter(function (x) { return !isInArray(this, node)})
.attr('opacity', 0.5);
}
)
.on('mouseout', function() {
d3.selectAll("rect").attr('opacity', 1.0);
});
使用一个小的辅助函数来检查一个值是否存在于数组中(在我们的例子中是 DOM 元素数组):
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
上下文中的完整代码(给定您的链接示例):
g.append("g")
.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; })
.selectAll("rect")
.data(function(d) { return keys.map(function(key) { return {key: key, value: d[key]}; }); })
.enter().append("rect")
.attr("x", function(d) { return x1(d.key); })
.attr("y", function(d) { return y(d.value); })
.attr("width", x1.bandwidth())
.attr("height", function(d) { return height - y(d.value); })
.attr("fill", function(d) { return z(d.key); })
.on('mouseover', function(d, i, node) {
d3.selectAll("rect")
.filter(function (x) { return !isInArray(this, node)})
.attr('opacity', 0.5);
}
)
.on('mouseout', function() {
d3.selectAll("rect").attr('opacity', 1.0);
});