首页 > 前端是否有办法判断img的图无法加载?

前端是否有办法判断img的图无法加载?

类似这种情况:

想让如果图裂了就display:none或者替换显示为默认图片,是否存在一个html的属性,或者css,可以判断图片裂了?(非alt属性)

如果html或css都做不到,js有什么简便的方法可以判断么?


onerror

<img src='/xxx/xxx/xxx.png' onerror='this.parentNode.removeChild(this)' />

可以參考:CSS裝飾加載失敗的圖片(譯)
https://.com/a/1190000004634661

原文
Styling Broken Images
by Ire Aderinokun 2016-03-08
http://bitsofco.de/styling-broken-images/


监听onerror事件吧


在img上绑定 onerror事件,调用本地替代图片src地址。


const img = new Image();

img.onerror = event => {
    console.log('load fail..')
};

img.src = "hahaha";

var oImg = new Image ,让这个oImg去存储正确的src地址,然后利用onload事件,能正常加载的话,再让之前的curImg去加载这个src,就可以了

【热门文章】
【热门文章】