欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jquery中判斷圖片是否存在的實現(xiàn)代碼

 更新時間:2023年06月14日 12:48:21   投稿:mdxy-dxy  
有時候我們需要判斷當前的圖片是否存在,方便后期做一些操作,當然也可以參考上一篇文章,如果不存在就替換位默認圖片

在網(wǎng)上搜索了好長時間,有些都沒有效果,后來終于實現(xiàn)了!需要的小伙伴們可以看下下面的代碼,希望可以幫助你們~

function isHasImg( src ){
    var img = new Image();
    img.src = src;
    img.onload = function(){
        if( img.width > 0 || img.height > 0  ){
            onImgExistNotify(img.src,true,3);
        }
        else{
            onImgExistNotify(img.src,false,2);
        }
    } 
    img.onerror = function(){
        onImgExistNotify(img.src,false,1);
    }   
}
function onImgExistNotify(src,bExist,iPlace){//圖片src是否存在通知
    if( bExist ){
        console.log("圖片src="+src+"存在"+iPlace);
    }
    else{
        console.log("圖片src="+src+"不存在"+iPlace);
    }
}

下面是其它網(wǎng)友的補充

利用圖片沒有加載完成的時候,寬高為0。我們很容易判斷圖片的一個加載情況。如下:

var t_img; // 定時器
var isLoad = true; // 控制變量
// 判斷圖片加載狀況,加載完成后回調(diào)
isImgLoad(function(){
    // 加載完成
});
// 判斷圖片加載的函數(shù)
function isImgLoad(callback){
    // 注意我的圖片類名都是cover,因為我只需要處理cover。其它圖片可以不管。
    // 查找所有封面圖,迭代處理
    $('.cover').each(function(){
        // 找到為0就將isLoad設為false,并退出each
        if(this.height === 0){
            isLoad = false;
            return false;
        }
    });
    // 為true,沒有發(fā)現(xiàn)為0的。加載完畢
    if(isLoad){
        clearTimeout(t_img); // 清除定時器
        // 回調(diào)函數(shù)
        callback();
    // 為false,因為找到了沒有加載完成的圖,將調(diào)用定時器遞歸
    }else{
        isLoad = true;
        t_img = setTimeout(function(){
            isImgLoad(callback); // 遞歸掃描
        },500); // 我這里設置的是500毫秒就掃描一次,可以自己調(diào)整
    }
}

如果還是不滿意,可以參考下面腳本之家小編寫的,不會死循環(huán)

function fixNDPic(){
var aimg=$(".xgcomm img");
	for(var i=0;i<aimg.length;i++){
		if(aimg[i].src.indexOf('img.jbzj.com')>-1){
		if(/do\/uploads\//.test(aimg[i].src)){
			aimg[i].onerror=function(){
				if (this.src.indexOf('img.jbzj.com')>-1){
this.src=this.src.replaceAll('img.jbzj.com','www.dbjr.com.cn');
				}
			}
		}
		}
	}
}
String.prototype.replaceAll = function(s1, s2) {
	return this.replace(new RegExp(s1, "gm"), s2);
}
fixNDPic()

到此這篇關于jquery中判斷圖片是否存在的實現(xiàn)代碼的文章就介紹到這了,更多相關jquery判斷圖片是否存在內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論