我有一个网页,里面有很多图片。有时映像不可用,因此在客户机的浏览器中显示一个损坏的映像。

我如何使用jQuery来获取图像集,过滤它到破碎的图像,然后替换src?


—我本以为用jQuery会更容易做到这一点,但事实证明使用纯JavaScript解决方案更容易,也就是Prestaul提供的解决方案。


当前回答

通过使用Prestaul的答案,我添加了一些检查,我更喜欢使用jQuery的方式。

<img src="image1.png" onerror="imgError(this,1);"/>
<img src="image2.png" onerror="imgError(this,2);"/>

function imgError(image, type) {
    if (typeof jQuery !== 'undefined') {
       var imgWidth=$(image).attr("width");
       var imgHeight=$(image).attr("height");

        // Type 1 puts a placeholder image
        // Type 2 hides img tag
        if (type == 1) {
            if (typeof imgWidth !== 'undefined' && typeof imgHeight !== 'undefined') {
                $(image).attr("src", "http://lorempixel.com/" + imgWidth + "/" + imgHeight + "/");
            } else {
               $(image).attr("src", "http://lorempixel.com/200/200/");
            }
        } else if (type == 2) {
            $(image).hide();
        }
    }
    return true;
}

其他回答

当OP正在寻找替换SRC时,我相信许多人遇到这个问题可能只希望隐藏损坏的图像,在这种情况下,这个简单的解决方案对我来说非常有用。

使用内联JavaScript:

<img src="img.jpg" onerror="this.style.display='none';"/>

使用外部JavaScript:

var images = document.querySelectorAll('img'); For (var I = 0;I < images.length;我+ +){ 图像[我]。Onerror = function() { this.style.display = '没有'; } } <img src='img.jpg' />

使用现代外部JavaScript:

document.querySelectorAll('img').forEach((img) => { img。Onerror = function() { This.style.display = 'none'; } }); <img src='img.jpg' />

参见浏览器对NodeList的支持。forEach和arrow函数。

这里有一个独立的解决方案:

$(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';
    }
  });
});

下面是一个使用JQuery包装的HTML5 Image对象的示例。为主图像URL调用load函数,如果加载导致错误,则用备份URL替换图像的src属性。

function loadImageUseBackupUrlOnError(imgId, primaryUrl, backupUrl) {
    var $img = $('#' + imgId);
    $(new Image()).load().error(function() {
        $img.attr('src', backupUrl);
    }).attr('src', primaryUrl)
}

<img id="myImage" src="primary-image-url"/>
<script>
    loadImageUseBackupUrlOnError('myImage','primary-image-url','backup-image-url');
</script>

我不确定是否有更好的方法,但我可以想到一个hack来获得它-你可以Ajax post到img URL,并解析响应,看看图像是否真的回来了。如果返回404或其他错误,则更换img。不过我估计过程会很缓慢。

多年来,这一直困扰着我。我的CSS修复在img上设置了一个背景图像。当动态图像src没有加载到前景时,img的bg上有一个占位符。如果你的图片有一个默认大小(例如高度,最小高度,宽度和/或最小宽度),这是有效的。

你会看到破碎的图像图标,但这是一种改进。成功测试到IE9。iOS、Safari和Chrome甚至都不会显示坏掉的图标。

.dynamicContainer img {
  background: url('/images/placeholder.png');
  background-size: contain;
}

添加一个小动画,让src在没有背景闪烁的情况下加载。Chrome浏览器在后台可以平滑淡出,但桌面版Safari浏览器却不能。

.dynamicContainer img {
  background: url('/images/placeholder.png');
  background-size: contain;
  animation: fadein 1s;                     
}

@keyframes fadein {
  0%   { opacity: 0.0; }
  50%  { opacity: 0.5; }
  100% { opacity: 1.0; }
}

.dynamicContainer img { background: url('https://picsum.photos/id/237/200'); background-size: contain; animation: fadein 1s; } @keyframes fadein { 0% { opacity: 0.0; } 50% { opacity: 0.5; } 100% { opacity: 1.0; } } img { /* must define dimensions */ width: 200px; height: 200px; min-width: 200px; min-height: 200px; /* hides broken text */ color: transparent; /* optional css below here */ display: block; border: .2em solid black; border-radius: 1em; margin: 1em; } <div class="dynamicContainer"> <img src="https://picsum.photos/200" alt="Found image" /> <img src="https://picsumx.photos/200" alt="Not found image" /> </div>