我有以下简单的 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 toiframe
, there are a lot of security concerns.
您可以使用 img
来加载您的 svg
而不是对象,它将以相同的方式加载,并且这确实会将事件触发回父级,因此,触发对父figure
的点击。
<figure>
<img width="100" height="100" src="./path/to/img.svg">
</figure>
下面有一个片段显示了使用 object
和 img
加载图像时的不同行为,第二个触发点击。
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/