Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

html - How does one use the onerror attribute of an img element

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...