2 回答

TA貢獻1806條經驗 獲得超5個贊
點擊會冒泡,這是正常的預期。為避免這種情況,請使用event.stopPropagation. 您還可以使用d3.events(當它們存在時...):
d3.event.stopPropagation();
這是演示,單擊矩形及其外部:
d3.select("rect").on("click", function() {
console.log("rectangle clicked");
d3.event.stopPropagation();
d3.select("body").on("click", function() {
console.log("body clicked")
})
})
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg>
<rect width="50" height="50" x="100" y="50"></rect>
</svg>

TA貢獻1816條經驗 獲得超6個贊
你可以這樣做:
// event listener: if events (circles) are clicked, instantiate pop-up
d3.selectAll(".events").on("click", function(d) {
console.log("event clicked!")
const currentCircle = this;
//disable hover event listeners
d3.selectAll(".events").on("mouseout", null);
d3.selectAll(".events").on("mouseover", null);
popup.transition()
.duration(200)
.style("opacity", .9);
popup.html(d.ArtistBio)
// if user clicks a SECOND time, anywhere, make popup disappear
d3.select("body").on("click", function(d) {
if(this !== currentCircle){
console.log("body clicked")
//hide popup
popup.transition()
.duration(200)
.style("opacity", 0);
//revert back to hover, unless user clicks again!
d3.selectAll(".events").on("mouseout", true);
d3.selectAll(".events").on("mouseover", true);
d3.selectAll(".events").on("mouseout", function(d) {
console.log("mousing out!")
popup.transition()
.duration(200)
.style("opacity", 0);
})
// mouseover event listers added back in
d3.selectAll(".events").on("mouseover", function(d) {
popup.transition()
.duration(200)
.style("opacity", .9);
popup.html(d.ArtistBio)
})
}
})
在 body 事件偵聽器中,檢查單擊的元素是否與單擊的當前圓/彈出窗口不同。
添加回答
舉報