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 事件侦听器中,检查单击的元素是否与单击的当前圆/弹出窗口不同。
添加回答
举报