admin 管理员组

文章数量: 1184232

background

css的background-image 没有像 img标签一样有onerror事件

<img src="./images/第一张.png" onerror="noExist();" /><script type="text/javascript"> 
function noExist(){ 
var img=event.srcElement; 
img.src="./images/第二张.png"; 
img.onerror=null; //当第二张也不存在时,防止死循环
} 
</script> 

当想要判断background-image图片是否存在时不能使用onerror,可以使用XMLHttpRequest判断是否404

  ImageIsExist(url) {let xmlHttp = new XMLHttpRequest();xmlHttp.open('Get', url, false);xmlHttp.send();if (xmlHttp.status === 404)return false;elsereturn true;}

本文标签: background