如何使用 img 元素的 onerror 属性 [英] How does one use the onerror attribute of an img element
问题描述
CSS:
.posting-logo-div {}.posting-logo-img {高度:120px;宽度:120px;}.posting-photo-div {高度:5px;宽度:5px;位置:相对;顶部:-140px;左:648px;}.posting-photo-img {高度:240px;宽度:240px;}
HTML:
<imgsrc="../images/some-logo1.jpg";onerror="this.src='../images/no-logo-120.jpg';"class="posting-logo-img";/><div id="照片";class="posting-photo-div"><imgsrc="../images/some-logo2.jpg";onerror="this.src='../images/no-logo-240.jpg';"class="posting-photo-img";/>
这似乎不适用于 Chrome 或 Mozilla,但适用于 IE.
这有效:
现场演示: http://jsfiddle.net/oLqfxjoz/
正如 Nikola 在下面的评论中指出的那样,如果备份 URL 也无效,一些浏览器会再次触发错误"事件,这将导致无限循环.我们可以通过简单地通过 this.onerror=null;
取消错误"处理程序来防止这种情况.
CSS:
.posting-logo-div {
}
.posting-logo-img {
height: 120px;
width: 120px;
}
.posting-photo-div {
height: 5px;
width: 5px;
position: relative;
top: -140px;
left: 648px;
}
.posting-photo-img {
height: 240px;
width: 240px;
}
HTML:
<div id="image" class="posting-logo-div">
<img
src="../images/some-logo1.jpg"
onerror="this.src='../images/no-logo-120.jpg';"
class="posting-logo-img"
/>
</div>
<div id="photo" class="posting-photo-div">
<img
src="../images/some-logo2.jpg"
onerror="this.src='../images/no-logo-240.jpg';"
class="posting-photo-img"
/>
</div>
This doesn't seem to work in Chrome or Mozilla but does work in IE.
This works:
<img src="invalid_link"
onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';"
>
Live demo: http://jsfiddle.net/oLqfxjoz/
As Nikola pointed out in the comment below, in case the backup URL is invalid as well, some browsers will trigger the "error" event again which will result in an infinite loop. We can guard against this by simply nullifying the "error" handler via this.onerror=null;
.
这篇关于如何使用 img 元素的 onerror 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!