首页 > 解决方案 > 如何设置图形标签的点击监听器?

问题描述

我有以下简单的 html 文档:

<!DOCTYPE html>
<html>
<head>
</head>

<body>
    <figure>
        <object class="" type="image/svg+xml" data="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350"></object>
    </figure>
</body>

<script>
    var figures = document.querySelectorAll('figure')
    for (let figure of figures) {
        figure.addEventListener("click", function () {
            console.log("hello")
        })
    }
</script>

</html>

但是,当我单击图像时没有任何反应。是否可以为图形标签设置点击监听器,如果没有,我可以使用哪些替代方案?

标签: javascripthtmlonclickonclicklistenerfigure

解决方案


问题不是标签figure而是object标签。该标签在嵌套上下文中运行,不会将事件传播回父级;因此,当您单击对象加载的图形时,它不会从嵌入的对象回火,永远不会点击您的figure.

object标签旨在运行嵌入式应用程序(过去的闪存应用程序),因此它具有类似于 的异常行为iframe,存在很多安全问题。

您可以使用 animg来加载您的svg而不是对象,它将以相同的方式加载,这确实将事件触发回父级,因此触发了对父级的点击figure

<figure>
  <img width="100" height="100" src="./path/to/img.svg">
</figure>

下面有一个片段显示了使用objectimg加载图像时的不同行为,第二个触发点击。

var figures = document.querySelectorAll('figure')
for (let figure of figures) {
  figure.addEventListener("click", function() {
    console.log("hello")
  })
}
<figure>
  <figcaption>I'm an object and I don't propagate events back to my parent</figcaption>
  <object width="100" height="100" type="image/svg+xml" data="https://upload.wikimedia.org/wikipedia/commons/f/fd/Ghostscript_Tiger.svg"></object>
</figure>

<figure>
  <figcaption>I'm an img and I propagate events back to my parent</figcaption>
  <img width="100" height="100" src="https://upload.wikimedia.org/wikipedia/commons/f/fd/Ghostscript_Tiger.svg">
</figure>


推荐阅读