Home >Web Front-end >CSS Tutorial >Why Does the onerror Attribute for Image Elements Behave Inconsistently Across Browsers?

Why Does the onerror Attribute for Image Elements Behave Inconsistently Across Browsers?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 10:22:29516browse

Why Does the onerror Attribute for Image Elements Behave Inconsistently Across Browsers?

Using the onerror Attribute for Image Elements

In HTML, the onerror attribute allows you to specify an action to be taken when an image fails to load. However, it has been observed that this attribute doesn't always work as expected in certain browsers.

In the example provided, where the onerror attribute is used to change the source of broken images, the behavior differs across browsers. To address this issue, a modified approach is required.

The updated code snippets below resolve the issue in Chrome and Mozilla while maintaining compatibility with IE:

<code class="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;
}</code>
<code class="html"><div id="image" class="posting-logo-div">
  <img src="invalid_link"
       onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';"
   class="posting-logo-img"
  />
</div>
<div id="photo" class="posting-photo-div">
  <img src="invalid_link"
       onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';"
       class="posting-photo-img"
  />
</div></code>

By nullifying the onerror handler using this.onerror=null; before changing the image's source, we can prevent an infinite loop that could occur if the backup URL is also invalid.

A live demonstration of this approach can be found at: http://jsfiddle.net/oLqfxjoz/

The above is the detailed content of Why Does the onerror Attribute for Image Elements Behave Inconsistently Across Browsers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn