在 D3 4.0 中的回调函数.on()方法传递 3 个参数 https://github.com/d3/d3-selection#handling-events:当前数据 (d)、当前索引 (i) 和当前组(节点)。
在鼠标悬停回调中,您可以selectAll("rect")
,并过滤掉当前组中的项目(node
)。通过此选择,您可以将不透明度设置为 0.5。鼠标移开时,您只需将所有不透明度设置回 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);
});