js當圖片返回404時如何展示默認圖片
阿新 • • 發佈:2017-12-22
默認 bin 失敗 span amp fault method 代碼 顯示
在做項目時遇到一個問題,當圖片返回失敗時,例如404的情況,不能正常的顯示,剛開始是用vue.js做的,部分代碼如下
<dt> <img v-bind:src="getHeadPic(user.headPic)" alt=""></dt>
methods:{ getHeadPic:function(headPic){ if(headPic != null && headPic != undefined && headPic != ‘‘){ return headPic ; }return "http://woxin2.jx139.com/cztx/images/ic_default_head.png"; }
通過vue.js動態綁定的方法,返回默認的頭像,這種情況只考慮到headPic 為 null 、undefined、 ”‘‘的這三種情況,而沒有考慮到返回的地址為404的情況,通過上網查資料得知,
img自身就帶有 onerror屬性,可以監控到圖片是否加載失敗的情況,於是乎,將代碼調整如下
<img v-bind:src="getHeadPic(user.headPic)" onerror="this.onerror=null; this.src=‘http://woxin2.jx139.com/cztx/images/ic_default_head.png‘">
至此,問題完美解決!
js當圖片返回404時如何展示默認圖片