js判断图片是否存在

2021-12-28  本文已影响0人  仰望天空的人
// 1 bug
    function isHasImg(pathImg) {
        var ImgObj = new Image();
        ImgObj.src = pathImg;
        if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
            return true;
        } else {
            return false;
        }
    }

// 2
    function CheckImgExists(imgurl) {
        var ImgObj = new Image(); //判断图片是否存在  
        ImgObj.src = imgurl;
        //没有图片,则返回-1  
        if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
            return true;
        } else {
            return false;
        }
    }

// 3
    function validateImage(url) {
        var xmlHttp;
        if (window.ActiveXObject) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } else if (window.XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        }
        xmlHttp.open("Get", url, false);
        xmlHttp.send();
        if (xmlHttp.status == 404)
            return false;
        else
            return true;
    }
<img src="./../image/109951166130586688.jpg" alt=""
    onerror="javascript:this.src='./../image/37f5e12a82766d690accd5ee86a08b0.png';">
上一篇 下一篇

猜你喜欢

热点阅读