img圖片不存在顯示預設圖
阿新 • • 發佈:2020-09-19
在專案中,我們使用img標籤載入圖片,有時候圖片地址有可能失效,獲取路徑問題,導致圖片載入失敗,img標籤就會顯示alt內容。這時候使用者體驗不是很好,所以就需要顯示一張預設圖片。
第一種方式:使用jquery_lazyload外掛實現圖片懶載入。只需要在src中寫上預設圖片地址即可。
<img src="/static/images/dlb.jpg" data-original="{{ item.get('CoverUrl') }}" alt="{{item.get('Name')}}" rel="nofollow">
第二種方式:在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'">
廣州vi設計http://www.maiqicn.com 辦公資源網站大全https://www.wode007.com
第三種方式:在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";
}
});