D3鼠标悬停在元素上与SVG鼠标移动冲突



我将鼠标悬停事件附加到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-eventsnone的行,这样它是"透明的"相对于鼠标事件来防止这种情况。修改后的例子