通过SVG背景传递鼠标事件

5

我有两个SVG元素,每个元素覆盖整个屏幕。

html,
body {
  height: 100%;
}

svg {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
<body>
  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <rect x=0 y=0 width=50 height=50 fill='#ff0000' onclick="console.log(1)"></rect>
  </svg>
  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <rect x=40 y=40 width=50 height=50 fill='#00ff00' onclick="console.log(2)"></rect>
  </svg>
</body>

即使这些正方形不重叠,由于带有绿色正方形的SVG覆盖整个屏幕并捕获任何点击事件,因此永远不会将点击事件传递给红色正方形。是否有办法在这两个正方形上都能够点击,而它们又不在同一个SVG中?
如何仅通过指针事件将点击事件传递到SVG?这样的解决方案可以很好地将点击事件传递给红色正方形,但前提是您愿意放弃绿色正方形上的所有事件。
2个回答

12

只需在svg标签上添加pointer-events none。并在svg内的所有其他元素上添加pointer-events auto。只使svg内的元素可点击,而不是父级svg标签。

在Chrome中有效。

html,
body {
  height: 100%;
}

svg {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  pointer-events:none;
}
svg *{
  pointer-events:auto;
}
<body>
  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <rect x=0 y=0 width=50 height=50 fill='#ff0000' onclick="console.log(1)"></rect>
  </svg>
  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <rect x=40 y=40 width=50 height=50 fill='#00ff00' onclick="console.log(2)"></rect>
  </svg>
</body>


pointer-events: none 会禁用 :hover CSS。 - ceving
这个答案对我来说真的很贴切 - 我有一个SVG被用作Open Layers地图上的径向菜单,但我仍然需要在SVG透明部分后面拖动地图,这个方法很有效! - R Brill

0

将您的svg元素包装在另一个svg元素中。请参见此处,了解为什么这样做是有效的:如果<svg>元素不是最外层元素,则无法成为指针事件的目标。最外层元素在此处是HTML上下文的一部分,因此它的行为类似于<div>

html,
body {
  height: 100%;
}

svg {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
<body>
  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <svg width="100%" height="100%">
      <rect x=0 y=0 width=50 height=50 fill='#ff0000' onclick="console.log(1)"></rect>
    </svg>
    <svg width="100%" height="100%">
      <rect x=40 y=40 width=50 height=50 fill='#00ff00' onclick="console.log(2)"></rect>
    </svg>
  </svg>
</body>


有趣的装置 - joopmicroop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接