I am Oliver

图片加载错误时显示默认图片

直接写

1
2
3
4
5
function imgError(image) {
    image.onerror = null; // prevent event bubble
    image.src = "/images/noimage.gif";
    return true;
}
1
<img src="image.png" onerror="imgError(this);"/>

使用 jQuery

1
2
3
4
5
6
7
8
$("img").error(function () {
    $(this).unbind("error").attr("src", "broken.gif");
});

//If you use this technique you can use the "one" method to avoid needing to unbind the event: 
$('img').one('error', function() { 
  this.src = 'broken.gif'; 
});

还有一种写法

1
2
3
4
5
6
7
8
9
10
$(window).load(function() {
  $('img').each(function() {
    if (!this.complete 
        || typeof this.naturalWidth == "undefined" 
        || this.naturalWidth == 0) {
      // image was broken, replace with your new image
      this.src = 'broken.gif';
    }
  });
});
打赏