在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');
});
In jQuery,I could do this using not
.有人知道D3.js的等价物吗?
发布于 2012-09-08 05:54:31
一种更简单的方法是使用D3运算符的功能:
vis.selectAll('circle.prospect').on("mouseover", function(d) {
var circleUnderMouse = this;
d3.selectAll('circle.prospect').transition().style('opacity',function () {
return (this === circleUnderMouse) ? 1.0 : 0.5;
});
});
这里有一个不同之处,那就是与原始代码不同,circleUnderMouse
元素的不透明度也将是平滑的动画。如果它已经完全不透明,那么可能不是什么大问题,否则您可以以类似的方式使用.duration()运算符,将circleUnderMouse时间加快到0,其他时间更长。
发布于 2012-09-08 05:45:30
如果您的元素具有唯一的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。
发布于 2012-09-07 23:52:07
您可以对选择执行filter
操作:
vis.selectAll('circle.prospect')
.on("mouseover", function(d) {
console.log(d);
var circleUnderMouse = this;
d3.selectAll('circle.prospect').filter(function(d,i) {
return (this !== circleUnderMouse);
}).transition().style('opacity','0.5');
d3.select(this).attr('opacity','1.0');
});
https://stackoverflow.com/questions/12321352
复制相似问题