我想在多个图表中突出显示同一维度(本例中为国家/地区)的元素。在生成 rect
或 circle
时为每个国家分配一个类,然后使用 querySeletorAll
查找所有匹配元素似乎可行,但是我想知道是否有更好的方法。这感觉有点老套。
请看这个block用于工作演示。
条形图和散点图都以相同的方式为它们的元素(rect
和 circle
)分配了类:
var enter = svgContainer.selectAll('rect')
.data(data)
.enter().append('rect')
.attr('class', function(d) { return "mycharts_bars_" + d.Country; })
然后悬停时高亮显示:
.on("mouseover", function(d) {
var hover_value = this.__data__.Country;
var hover_elems = document.querySelectorAll(`[class*="${hover_value}"]`);
for (let item of hover_elems) {
item.setAttribute('fill', 'hotpink');}
})
最佳答案
正如您在 source code 中看到的那样, d3.selectAll
已经在内部使用了 document.querySelectorAll
:
export default function(selector) {
return typeof selector === "string"
? new Selection([document.querySelectorAll(selector)], [document.documentElement])
: new Selection([selector == null ? [] : selector], root);
}
因此,您可以安全地使用 selectAll
,这会使您的代码更适合 D3 程序员。
但是,您的代码中存在一些问题:
首先,您不需要 var hover_value = this.__data__.Country;
。您已经将数据作为第一个参数!因此,它可以只是 d.Country
。
其次,如果你不想的话,你不需要处理类,只需选择元素即可。如果你愿意,你可以使用类,这不是什么大问题,但你绝对不需要那个 for...of
循环。根据经验,不要在 D3 代码中使用循环(在某些特定情况下需要使用循环,但这次不需要)。
综上所述,函数可以简单地是这样的:
d3.selectAll("circle, rect").attr("fill", function(e) {
return e.Country === d.Country ? "pink" : "grey"
});
或者,因为只有悬停在上面的矩形会改变颜色:
d3.select(this).attr("fill", "pink");
d3.selectAll("circle").attr("fill", function(e) {
return e.Country === d.Country ? "pink" : "grey"
});
作为旁注,这将更改页面中的所有 选定元素。我这样做只是因为在您的示例中,您的元素很少。如果在你的真实图表中你有数百个元素,更好的解决方案是先过滤它们,然后应用更改(在 mouseover
和 mouseout
上),这会给你更好的性能.
这里是你的代码更改:https://blockbuilder.org/GerardoFurtado/e54f2f0cc711b51be4b400627cac6f51
关于javascript - querySelectorAll 是在多个图表中选择元素的好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54097383/