通过SVG背景传递鼠标事件 [英] Passing Mouse Events through SVG Background

查看:110
本文介绍了通过SVG背景传递鼠标事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个SVG元素,每个元素都覆盖了整个屏幕.

I have two SVG elements, each covering the entire screen.

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中?

Even though the squares are not overlapping, click events will never be passed to the red square, since the SVG with the green square covers the whole screen and captures any click events. Is there any way to have click events on both of these squares, without them being in the same SVG?

类似于的解决方案我只能通过带有指针事件的SVG来进行点击吗?可以很好地将点击事件传递给红色方块,但前提是您可以丢弃绿色方块上的所有事件.

A solution like How can I pass ONLY clicks through a SVG with pointer-events? is great at passing click events through to the red square, but only if you're okay with discarding all events on the green square.

推荐答案

只需将指针事件都不添加到svg标记中.并在svg内的其他所有内容上添加自动指针事件.仅使svg内的元素可点击,而不使父svg标记可点击.

Just add pointer-events none to the svg tag. And on everything else inside the svg add pointer-events auto. Making only the elements inside the svg clickable, not the parent svg tag.

在chrome中工作.

Works in 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>

这篇关于通过SVG背景传递鼠标事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆