javascript - 如何设置图形标签的点击监听器?
问题描述
我有以下简单的 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>
但是,当我单击图像时没有任何反应。是否可以为图形标签设置点击监听器,如果没有,我可以使用哪些替代方案?
解决方案
问题不是标签figure
而是object
标签。该标签在嵌套上下文中运行,不会将事件传播回父级;因此,当您单击对象加载的图形时,它不会从嵌入的对象回火,永远不会点击您的figure
.
该
object
标签旨在运行嵌入式应用程序(过去的闪存应用程序),因此它具有类似于 的异常行为iframe
,存在很多安全问题。
您可以使用 animg
来加载您的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>
推荐阅读
- c++ - 为什么我的第二个功能(push2())不起作用?
- javascript - 将具有特定位置的多个对象分组三个js
- vb.net - 删除另一个面板内的面板
- python - 如何在不创建本地副本的情况下从在线 gzip 文件中读取数据?
- lambda - 如何为 serverless.yml 中的所有功能设置默认授权人
- html - 根据父 div 更改嵌套子 div
- php - Codeigniter - 不显示任何数据
- arrays - 使用Angular从具有另一组值的数组中查找匹配值的最佳方法
- c# - 如何通过 linq 查询读取所有代码并保存到单个集合中
- android - 在我按下android中的按钮之前如何使任何视图增长。(kotlin或java无关紧要)?