我們在項目開發中,可能會遇到圖片服務器宕機,圖片顯示異常,頁面相當不雅嚴重影響客戶體驗。下面記錄一下在項目中的解決方案:
在書寫HTML頁面的時候,給圖片添加一個錯誤類:
<img src="xxx.png" alt="圖片顯示錯誤" onerror="this.classList.add('error');">
然后配合css實現同時顯示錯誤圖片和alt文字提示:
img.error { display: inline-block; transform: scale(1); content: ''; color: transparent; } // 圖片顯示錯誤: 顯示缺省圖片 img.error::before { content: ''; position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: #f5f5f5 url(break.svg) no-repeat center / 50% 50%; } // 圖片顯示錯誤: 顯示缺省文字提示,這里attr()可以顯示當前標簽內的所有屬性,支持自定義屬性 img.error::after { content: attr(alt); position: absolute; left: 0; bottom: 0; width: 100%; line-height: 2; background-color: rgba(0,0,0,.5); color: white; font-size: 12px; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
這樣就可以看到圖片報錯之后,顯示的圖片和文字提示。
顯示效果如下圖第二幅圖所示:
注意:這里圖片地址和錯誤顯示圖片地址盡量不要放在同一服務器,因為如果圖片服務器宕機,那么替換圖片也顯示不出來了。
參考鏈接:https://www.zhangxinxu.com/wordpress/2020/10/css-style-image-load-fail/