我有一个简单的形象,许多直肠,超过100,我会说。为了美观起见,我想创造一个高光效果的鼠标点击。我还希望在用户单击新的rect时消除该效果,从而使这一效果更加直观。但是,如果不使用d3.selectAll()调用,就无法使其工作,因此我认为,如果这个项目变得更大,这种方法可能并不理想。以下是代码:
.on('click.highlight', function() {
//set any previously highlighted rects back to normal color/brightness
d3.selectAll('.highlight').transition().duration(250)
.style('fill', function(d) { return d3.rgb(d.color)})
d3.select(this).classed('highlight',true);
//now it's safe to assign the current highlighted rect a brighter hue... i think
d3.select(this).transition().duration(250)
.style('fill', function(d) { return d3.rgb(d.color).brighter(.5)})
})虽然这段代码做了我想要做的事情,但是在任何给定的时候,大概只有一个其他的highlight代码需要担心。因此,我不确定是否需要在这里使用d3.selectAll()。
那么,还有更有效的方法吗?如果可能的话,我想把它都保存在一个.on('click')函数中。
发布于 2017-08-04 16:00:34
如果您希望避免使用.selectAll,则可以创建包含最后单击的矩形的一个rect的选择。每次单击矩形时:
我使用变量highlightedRect保存将允许上述工作流的选择:
var svg = d3.select("body").append("svg")
.attr("width",600)
.attr("height",400);
var highlightedRect = d3.select(null);
var rects = svg.selectAll("rect")
.data(d3.range(1600))
.enter()
.append("rect")
.attr("y",function(d) { return Math.floor(d/50)*12; })
.attr("x",function(d) { return d%50 * 12 })
.attr("width",11)
.attr("height",11)
.attr("stroke","white")
.on("click",function(d) {
// Recolor the last clicked rect.
highlightedRect.attr("fill","black");
// Color the new one:
highlightedRect = d3.select(this);
highlightedRect.attr("fill","steelblue");
})<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
https://stackoverflow.com/questions/45510657
复制相似问题