javascript - 如何设置图形标签的点击监听器?

标签 javascript html onclick onclicklistener figure

我有以下简单的 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>

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

最佳答案

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

The object tag is meant to run embedded applications (flash apps back in the day) so it has an abnormal behaviour similar to iframe, there are a lot of security concerns.

您可以使用 img 来加载您的 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>

关于javascript - 如何设置图形标签的点击监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52174724/

相关文章:

javascript - 提交表单时 onclick 事件不起作用

javascript - 在我的 Google 搜索 API 调用中,它返回一个有效的 JSON,但每当我解析它以获取特定值时,我都会得到 Undefined

javascript - 如何为 TypeORM 指定 ormconfig.ts?

html - Bootstrap 表单布局

javascript - 调整背景图像大小的替代方法

javascript - Jquery onclick 不执行任何操作

jQuery UI 对话框 - 在对话框中打开外部动态 php 文件

javascript - JS继承原型(prototype)时如何传递参数?

javascript - 为 Bootstrap 和 Foundation CSS 框架命名空间

html - 自动完成不适用于 Chrome