如何处理HTML5图片标记中的未找到图片错误 [英] How to handle image not found error in html5 picture tag
问题描述
我正在尝试使用以下代码:
I am trying to use the below piece of code:
<picture>
<source media="(min-width: 1200px)" srcset="https://example.com/images/abc.jpg?resize=169,169">
<source media="(min-width: 992px)" srcset="https://example.com/images/cde.jpg?resize=132,132">
<img src="index_files/red_1.jpg" alt="Red 1">
</picture>
我面临的问题是,当abc.jpg或cde.jpg不可用时,它应该显示默认图像,例如default.jpg,甚至不显示red_1.jpg我在网站上提到了其他类似的话题,但是我不知道如何借助html处理问题.
the problem which I am facing is when abc.jpg or cde.jpg is not available it should show a default image say e.g., default.jpg and not even the red_1.jpg I referred to other similar topic in the website but i didnt get to know how to handle the problem with the help of html.
在这种情况下是否可以使用 onerror
,如果可以,在哪里以及如何使用?
Whether onerror
could be used in that case, if yes, where and how?
推荐答案
是的,使用 onerror
事件.然后,您只需更改 src
属性:
let image = document.querySelector('img');
image.onerror = function() {
if (this.src === 'default1.png') this.src = 'default2.png';
else if (this.src !== 'default2.png') this.src = 'default1.png';
}
这会将图片的 src
从原来的更改为'default1.png'
,然后,如果再次触发,则更改为'default2.png'
.
This will change the src
of the image from whatever it was to 'default1.png'
and then, if it fires again, to 'default2.png'
.
这篇关于如何处理HTML5图片标记中的未找到图片错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!