页面img图片不存在显示默认图代码

建站交流4年前 (2021-10-26)6480

在项目中,我们使用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使用方法链接:https://www.jq22.com/jquery-info390

第二种方式:在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_xI4khGko9WTAnF6b80e7becdddcc3802e2eb9389b506b49.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/01213fb80e7becdddcc3802e2eb9389b506b49.jpg
         }});


“页面img图片不存在显示默认图代码” 的相关文章

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。