在項目中,咱們使用img標籤加載圖片,有時候圖片地址有可能失效,獲取路徑問題,致使圖片加載失敗,img標籤就會顯示alt內容。這時候用戶體驗不是很好,因此就須要顯示一張默認圖片。jquery
第一種方式:使用jquery_lazyload插件實現圖片懶加載。只須要在src中寫上默認圖片地址便可。this
<img class="lazy" src="/static/images/dlb.jpg" data-original="{{ item.get('CoverUrl') }}" alt="{{item.get('Name')}}" rel="nofollow">spa
第二種方式:在img標籤上寫 onerror 方法。3d
<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標籤圖片加載出錯,就會給賦值默認圖片地址)blog
$('.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";
}});