img图片不存在显示默认图

在项目中,我们使用img标签加载图片,有时候图片地址有可能失效,获取路径问题,导致图片加载失败,img标签就会显示alt内容。这时候用户体验不是很好,所以就需要显示一张默认图片。

第一种方式:使用jquery_lazyload插件实现图片懒加载。只需要在src中写上默认图片地址即可。

  <img class="lazy" src="/static/images/dlb.jpg" data-original="{{ item.get('CoverUrl') }}" alt="{{item.get('Name')}}" rel="nofollow">

  jquery_lazyload使用方法链接。

第二种方式:在img标签上写 onerror 方法。

  <img src="http://pic0.iqiyipic.com/image/20180619/0f/da/v_114905674_m_601_m6_180_236.jpg" height="380px" width="200px"
onerror="this.src='https://gss0.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/zhidao/wh%3D600%2C800/sign=ee323c6c71cf3bc7e855c5eae1309699/3801213fb80e7becdddcc3802e2eb9389b506b49.jpg'">

  

第三种方式:在js中写(只要当前页面img标签图片加载出错,就会给赋值默认图片地址)

$('.img').each(function () {
if (!this.complete || typeof this.naturalWidth === "undefined" || this.naturalWidth === 0) {
this.src = "https://gss0.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/zhidao/wh%3D600%2C800/sign=ee323c6c71cf3bc7e855c5eae1309699/3801213fb80e7becdddcc3802e2eb9389b506b49.jpg";
    }
});
原文地址:https://www.cnblogs.com/wendj/p/10333280.html