SVG 鼠标事件传递(元素除外)

发布于 2025-01-15 05:13:27 字数 530 浏览 4 评论 0原文

我有一个透明的 SVG 画布作为其他元素的叠加层。我想要的是允许鼠标事件传递到下面的元素,但可见 svg 元素上的事件也可以工作。我可以得到它,以便 svg 捕获事件,或者让它们在 svg 元素上使用 css 指针事件 (none|auto),但无法弄清楚如何仅捕获 svg 的可见元素上的事件。

我动态创建 svg 元素,例如

C=document.createElementNS("http://www.w3.org/2000/svg","circle")
C.setAttributeNS(null,"r",curve_radius)
C.setAttributeNS(null,"cx",x)
C.setAttributeNS(null,"cy",y)
C.setAttributeNS(null,"fill","rgb(0,0,255)")
C.setAttributeNS(null,"stroke","rgb(0,0,255)")     
C.setAttributeNS(null,"stroke-width","1")

svg.appendChild(C) ;

I have a transparent SVG canvas as an overlay to other elements. What I want is to allow mouse event pass through to the elements below, but events on the visible svg elements to also work. I can get it so the svg captures events, or lets them though with css pointer-events (none|auto) on the svg element, but can't work out how to capture events only on the visible elements of the svg.

I create the svg elements dynamically, e.g.

C=document.createElementNS("http://www.w3.org/2000/svg","circle")
C.setAttributeNS(null,"r",curve_radius)
C.setAttributeNS(null,"cx",x)
C.setAttributeNS(null,"cy",y)
C.setAttributeNS(null,"fill","rgb(0,0,255)")
C.setAttributeNS(null,"stroke","rgb(0,0,255)")     
C.setAttributeNS(null,"stroke-width","1")

svg.appendChild(C) ;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

软甜啾 2025-01-22 05:13:27

您找到了指针事件。我认为这只是以正确的方式进行调整的问题。在这里,我“禁用”了 上的指针事件,同时指定 的笔画应该接受事件。

document.getElementById('bg').addEventListener('click', e => {
  console.log(e.target.nodeName);
});
#bg {
  background-color: orange;
  position: relative;
  width: 200px;
  height: 200px;
}

svg {
  pointer-events: none;
  position: absolute;
}

circle {
  pointer-events: stroke;
}

p {
  position: absolute;
  top: 100px;
  left: 40px;
}
<div id="bg">
  <p>Text</p>
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="200">
    <circle cx="5" cy="5" r="4" stroke="red" fill="none"/>
  </svg>
</div>

You found pointer-events. I think it is just a matter of tweaking it in the right way. Here I "disable" pointer-events on the <svg> and at the same time specifying that the stroke of the <circle> should take event.

document.getElementById('bg').addEventListener('click', e => {
  console.log(e.target.nodeName);
});
#bg {
  background-color: orange;
  position: relative;
  width: 200px;
  height: 200px;
}

svg {
  pointer-events: none;
  position: absolute;
}

circle {
  pointer-events: stroke;
}

p {
  position: absolute;
  top: 100px;
  left: 40px;
}
<div id="bg">
  <p>Text</p>
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" width="200">
    <circle cx="5" cy="5" r="4" stroke="red" fill="none"/>
  </svg>
</div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文