1
我有一個散點圖,點擊事件和畫筆事件都會突出顯示點。如果我先刷過一些圓圈,然後單擊一個圓圈,畫筆仍然可見。如何在D3.js中單擊圓圈時隱藏畫筆?
我該如何做到這一點,所以當單擊一個圓圈時刷子消失,但之後仍然可用?
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<style>
#plot{
border-style: solid;
border-width: 4px;
border-color: lightgray;
display: inline-block;
line-height: 0;
}
circle{
fill: blue;
}
.highlight{
fill: red;
}
</style>
<body>
<script src="d3.js"></script>
<div id="plot">
<script>
(function(){
var data = [];
for(i = 0; i < 100; i++){
var x = Math.random();
var y = Math.random();
data.push({x: x, y: y});
}
var xScale = d3.scale.linear()
.domain([0, 1])
.range([0, 400]);
var yScale = d3.scale.linear()
.domain([0, 1])
.range([400, 0]);
var svg = d3.select("#plot").append("svg")
.attr("width", 400)
.attr("height", 400)
var brush = d3.svg.brush()
.x(xScale)
.y(yScale)
.on("brushstart", brushstart)
.on("brushend", brushend);
function brushstart(){
d3.selectAll("circle")
.classed("highlight", false);
}
function brushend(){
var e = brush.extent();
d3.selectAll("circle").filter(function(d){
return xScale(d.x) >= xScale(e[0][0]) &&
yScale(d.y) <= yScale(e[0][1]) &&
xScale(d.x) <= xScale(e[1][0]) &&
yScale(d.y) >= yScale(e[1][1]);
})
.classed("highlight", true);
}
svg.append("g")
.classed("brush", true)
.call(brush);
svg.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("r", 6)
.attr("cx", function(d){ return xScale(d.x) })
.attr("cy", function(d){ return yScale(d.y) })
.on("click", function(){
d3.selectAll("circle").classed("highlight", false);
d3.select(this).classed("highlight", true);
});
})();
</script>
</div>
</body>
</html>
我能夠使刷d3.selectAll("brush").remove()
或d3.selectAll("brush").style("display", "none")
消失,但刷不能事後使用。
感謝。我曾嘗試過,但那是在我正確地將一個班級分配給我的筆刷之前。 – user2829582
不客氣! :-) –