我已将鼠标悬停事件附加到 SVG 元素内的一个元素(例如,一个圆圈)。我还需要一个与 SVG 元素/“背景”本身关联的“mousemove”事件处理程序。然而,它们似乎有冲突:当鼠标悬停在圆上时,附加到圆上的处理程序不会取代与 SVG 元素本身关联的处理程序。
如何让圆圈的鼠标悬停取代 SVG 元素的事件处理程序?我需要它们,但只希望鼠标悬停在圆上触发,鼠标移动由 SVG 元素中其他任何位置的移动触发。
可以在这个 JSFiddle 中看到一个简化的例子:http://jsfiddle.net/aD8x2/ (下面的JS代码)。如果您单击一个圆圈(开始一行)然后将鼠标悬停在另一个圆圈上,您将看到与鼠标悬停在该圆圈上时触发的两个事件相关的颜色闪烁。
var svg = d3.select("div#design")
.append("svg")
.attr("width", "500").attr("height", "500");
svg.selectAll("circle").data([100, 300]).enter().append("circle")
.attr("cx", function(d) { return d; })
.attr("cy", function(d) { return d; })
.attr("r", 30)
.on("mouseover", function () {
d3.select(this).attr("fill", "red");
})
.on("mouseout", function() {
d3.select(this).attr("fill", "black");
})
.on("click", function() {
svg.append("line")
.attr(
{
"x1": d3.select(this).attr("cx"),
"y1": d3.select(this).attr("cy"),
"x2": d3.select(this).attr("cx"),
"y2": d3.select(this).attr("cy")
})
.style("stroke-width", "10")
.style("stroke", "rgb(255,0,0)");
});
svg.on("mousemove", function() {
var m = d3.mouse(this);
svg.selectAll("line")
.attr("x2", m[0])
.attr("y2", m[1]);
});
最佳答案
在您的情况下,它实际上是导致问题的行而不是 SVG。也就是说,您将鼠标移到正在绘制的线上,因此会为圆触发 mouseout
事件。
您可以通过将行的 pointer-events
设置为 none
来防止这种情况发生,因此它对于鼠标事件是“透明的”。修改示例 here .
关于javascript - 元素上的 d3 鼠标悬停与 svg mousemove 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22636629/