带有 SVG 元素和 G 的 StopPropagation() [英] StopPropagation() with SVG element and G
问题描述
我创建了一个具有 .on("click")
行为的 SVG 元素,并用 .on("click")
附加了 g 元素,并认为我可以使用d3.event.stopPropagation()
以防止 SVG 单击事件与 g 单击事件一起触发.相反,这两个事件都会继续触发.所以我必须把 stopPropagatio
n 放在错误的地方.
I created an SVG element with an .on("click")
behavior and appended g elements with .on("click")
and thought that I could use d3.event.stopPropagation()
to keep the SVG click event from firing with the g click event. Instead, both events continue to fire. So I must be placing stopPropagatio
n in the wrong place.
svg = d3.select("#viz").append("svg:svg")
.attr("width", 800)
.attr("height", 800)
.on("mousedown", mousedown);
sites = svg.selectAll("g.sites")
.data(json.features)
.enter()
.append("svg:g")
.on("click", siteClick)
;
sites.append("svg:circle")
.attr('r', 5)
.attr("class", "sites")
;
function mousedown() {
console.log("mouseDown");
}
function siteClick(d, i) {
d3.event.stopPropagation();
console.log("siteClick");
}
推荐答案
您似乎混淆了 click
和 mousedown
事件.调用 stopPropagation
一次只会阻止单个事件的传播,而这些是单独的事件.
You seem to be mixing up the click
and mousedown
events. Calling stopPropagation
will only prevent propagation of a single event at a time, and these are separate events.
通常,点击手势会依次引发 mousedown
、mouseup
和 click
事件.
Typically, a click gesture will cause mousedown
, mouseup
and click
events, in that order.
您可以在子元素上保留 click
事件处理程序,并使用 stopPropagation
调用添加 mousedown
事件处理程序,这应该可以实现你在追求什么.
You can keep the click
event handler on the child elements and add a mousedown
event handler with a stopPropagation
call, and that should achieve what you're after.
这是一个示例,演示了它在与您类似的情况下的使用.
Here is an example demonstrating its use in a similar situation to yours.
这篇关于带有 SVG 元素和 G 的 StopPropagation()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!