SVG Snap 悬停在分组元素上

SVG Snap hover over grouped elements

我有一个组,其中包含一些元素: 一条路径(黑色)和 2 个矩形(粉色和蓝色)

他们都属于同一个组。

基本上,我想做的是当鼠标悬停在组上时我想执行一个函数,所以我这样做:

  group.hover(function(e){ //set up hovering
           console.log("hover bubble");
       }, function(e) {
           console.log("unhover bubble");
    });

但是组的工作方式是组中的每个元素都具有悬停功能...所以如果我将鼠标悬停在黑色路径上然后移动到粉红色矩形,它会认为这是黑色路径的悬停然后将鼠标悬停在粉红色矩形上。这不是我想要的。

我只想将鼠标悬停在整个分组区域上,并在整个分组区域悬停时执行函数,并在整个分组区域取消悬停时执行取消悬停函数。

有点像如果所有这些元素都在 div 中,我将鼠标悬停在 div..

我可以看到你有 snap.svgraphael 作为标签,但这里是使用纯 JS 的解决方案。

我制作了一个简单的 SVG,其中包含一个黑色矩形(您的路径)、一个粉色矩形和一个蓝色矩形。当您将鼠标悬停在该组上时,它会在控制台中记录 "hover bubble",当您将鼠标悬停在该组上时,它会记录 "unhover bubble":

var group = document.querySelector("g");

function isInside(node, target) {
    for (; node != null; node = node.parentNode)
      if (node == target) return true;
}

group.addEventListener("mouseover", function(event) {
    if (!isInside(event.relatedTarget, group))
      console.log("hover bubble");
});

group.addEventListener("mouseout", function(event) {
    if (!isInside(event.relatedTarget, group))
       console.log("unhover bubble");
});
svg {
  background-color: tan;
 }
<svg width="300" height="300">
 <g>
  <rect x="40", y="40", width="220", height="220", fill="black"></rect>
  <rect x="60", y="60", width="80", height="80", fill="pink"></rect>
  <rect x="160", y="60", width="80", height="80", fill="blue"></rect>
 </g>
</svg>

这是您的问题的原因:

Whenever the mouse pointer enters or leaves a node, a "mouseover" or "mouseout" event fires [...] Unfortunately, creating such an effect is not as simple as starting the effect on "mouseover" and ending it on "mouseout". When the mouse moves from a node onto one of its children, "mouseout" fires on the parent node, though the mouse did not actually leave the node’s extent. To make things worse, these events propagate just like other events, and thus you will also receive "mouseout" events when the mouse leaves one of the child nodes of the node on which the handler is registered.

代码和引用的来源:Eloquent JavaScript,来自 Marijn Haverbeke。