本文介绍了如何使用img元素的onerror属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CSS:

  .posting-logo-div {} 
.posting-logo-img {height: 120像素;宽度:120像素; }
.posting-photo-div {height:5px; width:5px; position:relative; top:-140px; left:648px; }
.posting-photo-img {height:240px;宽度:240像素; }

HTML:

 < div id =imageclass =posting-logo-div>< img src =../ images / some-logo1.jpgonerror =this.src =' ../images/no-logo-120.jpg;类= 张贴-标志-IMG >< / DIV> 
< div id =photoclass =posting-photo-div>< img src =../ images / some-logo2.jpgonerror =this.src ='.. /images/no-logo-240.jpg;类= 张贴-光IMG >< / DIV>

这似乎在Chrome或Mozilla中无法正常工作,但在IE中可以正常工作。

解决方案

这样做:

 < img src =invalid_link
onerror =this.onerror = null; this.src ='https://placeimg.com/200/300/animals';
>

现场演示:

正如Nikola在下面的评论中所指出的,在如果备份URL也是无效的,一些浏览器将再次触发错误事件,这将导致无限循环。我们可以通过简单地通过 this.onerror = null; 来取消error处理程序来防范这种情况。


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属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 09:01