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

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


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


当前回答

我认为我有一个更优雅的方式与事件委托和事件捕捉窗口的错误,即使备份映像加载失败。

img { width: 100px; height: 100px; } <script> window.addEventListener('error', windowErrorCb, { capture: true }, true) function windowErrorCb(event) { let target = event.target let isImg = target.tagName.toLowerCase() === 'img' if (isImg) { imgErrorCb() return } function imgErrorCb() { let isImgErrorHandled = target.hasAttribute('data-src-error') if (!isImgErrorHandled) { target.setAttribute('data-src-error', 'handled') target.src = 'backup.png' } else { //anything you want to do console.log(target.alt, 'both origin and backup image fail to load!'); } } } </script> <img id="img" src="error1.png" alt="error1"> <img id="img" src="error2.png" alt="error2"> <img id="img" src="https://i.stack.imgur.com/ZXCE2.jpg" alt="avatar">

重点是:

将代码放在头部,并作为第一个内联脚本执行。因此,它将侦听脚本执行后发生的错误。 使用事件捕获来捕获错误,特别是那些没有冒泡的事件。 使用事件委托,避免在每个图像上绑定事件。 在给error img元素一个backup.png文件之后,给它们一个属性,以避免backup.png文件的消失和后续的无限循环,如下所示:

img错误- - - - - - > backup.png - >错误- > backup.png - >错误- >…

其他回答

我也有同样的问题。这个代码在我的案子上很有效。

// Replace broken images by a default img
$('img').each(function(){
    if($(this).attr('src') === ''){
      this.src = '/default_feature_image.png';
    }
});

我找不到适合我需要的脚本,所以我做了一个递归函数来检查损坏的图像,并尝试每四秒重新加载它们,直到它们修复。

我将它限制为10次尝试,因为如果它没有加载,那么图像可能不会出现在服务器上,函数将进入一个无限循环。不过我仍在测试中。请随意调整它:)

var retries = 0;
$.imgReload = function() {
    var loaded = 1;

    $("img").each(function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {

            var src = $(this).attr("src");
            var date = new Date();
            $(this).attr("src", src + "?v=" + date.getTime()); //slightly change url to prevent loading from cache
            loaded =0;
        }
    });

    retries +=1;
    if (retries < 10) { // If after 10 retries error images are not fixed maybe because they
                        // are not present on server, the recursion will break the loop
        if (loaded == 0) {
            setTimeout('$.imgReload()',4000); // I think 4 seconds is enough to load a small image (<50k) from a slow server
        }
        // All images have been loaded
        else {
            // alert("images loaded");
        }
    }
    // If error images cannot be loaded  after 10 retries
    else {
        // alert("recursion exceeded");
    }
}

jQuery(document).ready(function() {
    setTimeout('$.imgReload()',5000);
});
(window.jQuery || window.Zepto).fn.fallback = function (fallback) {
  return this.one('error', function () {
    var self = this;
    this.src = (fallback || 'http://lorempixel.com/$width/$height').replace(
      /\$(\w+)/g, function (m, t) { return self[t] || ''; }
    );
  });
};
    

你可以传递一个占位符路径,并通过$*访问失败图像对象的所有属性:

$('img').fallback('http://dummyimage.com/$widthx$height&text=$src');

http://jsfiddle.net/ARTsinn/Cu4Zn/

如果有人像我一样,试图将错误事件附加到动态HTML img标记,我想指出的是,有一个陷阱:

显然,img错误事件不会在大多数浏览器中冒泡,这与标准的说法相反。

所以,像下面这样的代码是行不通的:

$(document).on('error', 'img', function () { ... })

希望这对其他人有所帮助。我希望我能在这个帖子里看到这个。但是,我没有。我把它加起来

多年来,这一直困扰着我。我的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>