在网上搜索了好长时间,有些都没有效果,后来终于实现了!需要的小伙伴们可以看下下面的代码,希望可以帮助你们~
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);
}
}
本文分享了一段用于检测图片链接是否有效的JavaScript代码。通过创建Image对象并监听其onload和onerror事件,可以判断图片是否能成功加载。此方法适用于网页开发中对图片资源的预加载检查。
851

被折叠的 条评论
为什么被折叠?



