首页 > 解决方案 > HTML

带有 SVG onclick 问题

问题描述

我有一个带有子对象标签的父 div,其中包含我的 svg。

我正在尝试捕获对我的图像的点击,但它不起作用。

在示例代码片段中,仅当在显示的 svg 之外单击一次时才会显示警报。

HTML:

<div class="calendarWidget" onclick="alert('test');">
    <span>
        <object  onclick="alert('test1');" data="https://www.multiservicetolls.com/wp-content/uploads/revslider/assets/svg/busy-icons-svg/folder-private.svg" type="image/svg+xml"></object>
    </span>
</div>

CSS:

.calendarWidget {
  position: fixed;
  max-width: 200px;
  width: 200px;
  right: 20px;
  bottom: 20px;
  background-color:green;
  z-index: 1;
}

JSFiddle

由于我的要求,我无法在 svg 中编写脚本代码。

标签: jqueryhtmlcsssvgz-index

解决方案


可能最简单的方法是将处理程序保留在 div 上,并将浏览器设置为使用 css 忽略 svg 上的鼠标事件pointer-events: none;。运行下面的代码片段以查看它是否有效(为了演示,我将 svg 移到了左上角)。

.calendarWidget {
  position: fixed;
  max-width: 200px;
  width: 200px;
  left: 20px;
  top: 20px;
  background-color:green;
  z-index: 1;
}
.ignoreMouse{
  pointer-events: none;
}
<div class="calendarWidget" onclick="alert('test');">
  <span>
    <object class="ignoreMouse" data="https://www.multiservicetolls.com/wp-content/uploads/revslider/assets/svg/busy-icons-svg/folder-private.svg" type="image/svg+xml"></object>
   </span>
</div>


推荐阅读