javascript - 元素上的 d3 鼠标悬停与 svg mousemove 冲突

标签 javascript svg d3.js

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

相关文章:

javascript - NodeJS 发出事件未触发

php - 在 HTML 中以 SVG 格式显示图像

css - 多个 CSS 关键帧动画在 SVG 路径上有延迟

javascript - C3.js 加载功能不工作

javascript - 我无法解释以下输出的结果

javascript - jvectormap 仅显示特定区域的标签

javascript - React hooks - 不能在普通异步函数中使用 hook?

html - CSS改变svg元素的路径

javascript - 在D3.js中动态创建节点

javascript - 根据下拉菜单选择重绘 d3 map