在 D3.js 中工作时,我想选择与当前元素的选择器匹配的所有元素除外。
原因是我想将鼠标悬停在一个圆圈上,并使所有其他具有相同类别的圆圈变成浅蓝色,但当前圆圈保持相同的颜色。
这是我目前拥有的:
vis.selectAll('circle.prospect')
.on("mouseover", function(d) {
console.log(d);
d3.selectAll('circle.prospect').transition().style('opacity','0.5');
d3.select(this).attr('opacity','1.0');
});
在 jQuery 中,我 could do this using not
。有人知道 D3.js 的等效项吗?
最佳答案
如果您的元素具有唯一的 CSS 可访问标识符,您可以使用 :not()
选择器。一些潜在的例子:
d3.selectAll("circle.prospect:not(#" + this.id + ")");
d3.selectAll("circle.prospect:not(." + someUniqueClassFrom(d) + ")");
d3.selectAll("circle.prospect:not([uniqueAttr=" + this.getAttribute('uniqueAttr') + "])");
原因d3.selectAll('circle.prospect:not(this)')
不起作用是因为它只是字面意思是过滤掉任何 <this></this>
元素 - 这显然不是你的意图,因为它已经只选择 <circle></circle>
无论如何,元素都不会产生任何影响。
即使您通常不应用某些独特的 DOM 属性,也没有理由不能暂时设置一个:
vis.selectAll('circle.prospect')
.on("mouseover", function(d) {
this.id = 'temp-' + Math.random();
d3.selectAll('circle.prospect:not(#' + this.id + ')').transition().style('opacity','0.5');
d3.select(this).attr('opacity','1.0');
this.id = '';
});
但是,如果您的元素尚未分配 ID,我认为 Ian Roberts 的解决方案可能就是我会做的,而不是这种临时标识符 hack。
关于javascript - 相当于 D3.js 中 jQuery 的 'not' 选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12321352/