我有以下简单的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>
但是,单击图像时没有任何反应。是否可以为数字标签设置on click侦听器,如果没有,我可以使用哪些替代方案?
问题不是figure
而是object
tag。此标记在嵌套上下文中运行,该上下文不会将事件传播回父级;因此,当您单击对象加载的图形时,它不会从嵌入对象反射回来,永远不会到达您的figure
上的点击。
object
tag用于运行嵌入式应用程序(当天回来的Flash应用程序),因此它具有类似于iframe
的异常行为,存在许多安全问题。
您可以使用img
加载svg
而不是对象,它将以相同的方式加载,这会将事件激发回父级,因此,触发父级figure
上的点击。
<figure>
<img width="100" height="100" src="./path/to/img.svg">
</figure>
Bellow有一个片段显示使用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>
您可以像对待任何其他元素一样向figure
元素添加单击事件处理程序。当JavaScript运行并尝试绑定click事件时,您的figure元素可能不存在于DOM中。要尝试的一件事是确保你的数字阵列像你期望的那样回归。另一件需要注意的是你的for of
循环,你的figure
变量是你所期望的。
const myFigure = document.querySelector('#myFigure');
myFigure.onclick = (evt) => {
console.log('I was just clicked');
}
<figure id="myFigure">
<img src="https://via.placeholder.com/350x150" />
</figure>
var figures = document.getElementsByTagName('figure');
for (let i = 0; i < figures.length; i++) {
figures[i].onclick = function (e) {
console.log("hello from figure: " + i);
};
}
<figure>
<img style="width: 100px; height: 100px;" src="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350" />
</figure>
<br><br>
<figure>
<img style="width: 100px; height: 100px;" src="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350" />
</figure>
<br><br>
<figure>
<img style="width: 100px; height: 100px;" src="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350" />
</figure>
<br><br>
<figure>
<img style="width: 100px; height: 100px;" src="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350" />
</figure>