jQuery / JavaScript替换损坏的图像

时间:2020-03-06 14:21:24  来源:igfitidea点击:

我有一个包含一堆图像的网页。有时,该图像不可用,因此在客户端的浏览器中会显示损坏的图像。

如何使用jQuery获取图像集,将其过滤为损坏的图像,然后替换src?

-我认为使用jQuery会更容易,但是事实证明,仅使用纯JavaScript解决方案(即Prestaul提供的解决方案)要容易得多。

解决方案

处理图像的onError事件以使用JavaScript重新分配其源:

function imgError(image) {
    image.onerror = "";
    image.src = "/images/noimage.gif";
    return true;
}
<img src="image.png" onerror="imgError(this);"/>

或者没有JavaScript函数:

<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />

以下兼容性表列出了支持错误工具的浏览器:

http://www.quirksmode.org/dom/events/error.html

我相信这就是我们所追求的:jQuery.Preload

这是演示中的示例代码,我们指定了加载和未找到的图像,并且一切就绪:

$('#images img').preload({
    placeholder:'placeholder.jpg',
    notFound:'notfound.jpg'
});

我不确定是否有更好的方法,但是我可以想到一个破解方法,可以将Ajax发布到img URL,然后解析响应以查看图像是否真的回来了。如果它以404或者类似的形式返回,则换掉img。虽然我希望这会很慢。

这是一个独立的解决方案:

$(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 = 'http://www.tranism.com/weblog/images/broken_ipod.gif';
    }
  });
});

我使用内置的error处理程序:

$("img").error(function () {
  $(this).unbind("error").attr("src", "broken.gif");
});

在1.8或者更高版本中不建议使用error()。

$(window).bind('load', function() {
$('img').each(function() {
    if((typeof this.naturalWidth != "undefined" &&
        this.naturalWidth == 0 ) 
        || this.readyState == 'uninitialized' ) {
        $(this).attr('src', 'missing.jpg');
    }
}); })

资料来源:http://www.developria.com/2009/03/jquery-quickie---broken-images.html