【问题标题】:d3 mouseover on element conflicts with svg mousemoved3 mouseover 元素与 svg mousemove 冲突
【发布时间】:2014-03-25 13:51:10
【问题描述】:

我已将鼠标悬停事件附加到 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]);
    });

【问题讨论】:

    标签: javascript svg d3.js


    【解决方案1】:

    在您的情况下,它实际上是导致问题的线路而不是 SVG。也就是说,您将鼠标移到正在绘制的线条上,因此会为圆圈触发 mouseout 事件。

    您可以通过将行的pointer-events 设置为none 来防止这种情况发生,因此它对于鼠标事件是“透明的”。修改示例here

    【讨论】:

    • 完美。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 2013-11-22
    相关资源
    最近更新 更多