jQuery/JavaScript to replace broken images

后端 未结 30 2502
我寻月下人不归
我寻月下人不归 2020-11-21 05:50

I have a web page that includes a bunch of images. Sometimes the image isn\'t available, so a broken image is displayed in the client\'s browser.

How do I use jQuery

30条回答
  •  无人共我
    2020-11-21 06:22

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

    You can pass a placeholder path and acces in it all properties from the failed image object via $*:

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

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

提交回复
热议问题