如何使用img元素的onerror属性

Sha*_*ukh 33 html css image onerror

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; }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

这在Chrome或Mozilla中似乎不起作用,但在IE中可以使用.

Šim*_*das 105

这有效:

<img src="invalid_link"
     onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';"
>
Run Code Online (Sandbox Code Playgroud)

现场演示: http ://jsfiddle.net/oLqfxjoz/

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

  • 如果"http://placekitten.com/100/100"不存在,这可能会非常危险,因为浏览器会持续敲击"http://placekitten.com/100/100"网址.有关解决方案,请参见http://stackoverflow.com/questions/92720/jquery-javascript-to-replace-broken-images (5认同)
  • @ŠimeVidas:那是因为Chrome只评估一次错误,而所有其他浏览器都是连续执行 - 为了避免循环它应该是这样的:`onerror ="this.onerror = null; this.src ='http:// placekitten. COM/100/100' ;"` (4认同)