禁止某些 svg 子元素的鼠标交互

Inhibit mouse interactions for certain svg child elements

本文关键字:鼠标 交互 元素 svg 禁止      更新时间:2023-09-26

这是一个画了一个圆圈的svg:

svg = d3.select("body").append("svg")
     .on("mouseover", function() { console.log("callback");} );
svg.append("circle")
     .attr("cx", 50)
     .attr("cy",50)
     .attr("r",20)
     .attr("fill","red");

为什么当我将鼠标悬停在circle上时mouseover触发?我假设是因为它是其父svg的子元素?

但我想禁止这种行为。我该怎么做?

鼠标悬停函数上的参数似乎没有在事件中传递,所以我想出了这个解决方案。

svg = d3.select("body").append("svg")
     .on("mouseover", function() {
         var event = window.event;
         if (event.target.nodeName === "svg") {
             console.log("callback");    
         }
     });
svg.append("circle")
     .attr("cx", 50)
     .attr("cy",50)
     .attr("r",20)
     .attr("fill","red");
如果要

禁止指针交互,请在该元素上设置指针事件="none"。

.attr("pointer-events","none")

容器元素不会在 SVG 中触发鼠标事件。 仅当您将鼠标悬停在其包含的任何子图形元素上时,才会触发该事件。