jQuery / JavaScript替换损坏的图像

孤街浪徒 提交于 2020-02-26 14:02:04

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

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


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


#1楼

如果像我这样的人尝试将error事件附加到动态HTML img标签上,我想指出的是,有一个陷阱:

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

因此,类似以下内容将不起作用

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

希望这对其他人有帮助。 我希望我已经在此线程中看到了这一点。 但是,我没有。 所以,我添加了它


#2楼

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

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

编辑:jQuery 1.8及更高版本中不建议使用error()方法。 相反,您应该使用.on("error")代替:

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

#3楼

;(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/


#4楼

CoffeeScript变体:

我修复了Turbolinks的一个问题,即使该图像确实存在,有时也会在Firefox中引发.error()方法。

$("img").error ->
  e = $(@).get 0
  $(@).hide() if !$.browser.msie && (typeof this.naturalWidth == "undefined" || this.naturalWidth == 0)

#5楼

我通过以下两个简单功能解决了我的问题:

function imgExists(imgPath) {
    var http = jQuery.ajax({
                   type:"HEAD",
                   url: imgPath,
                   async: false
               });
    return http.status != 404;
}

function handleImageError() {
    var imgPath;

    $('img').each(function() {
        imgPath = $(this).attr('src');
        if (!imgExists(imgPath)) {
            $(this).attr('src', 'images/noimage.jpg');
        }
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!