js判断img是否存在

利用image对象的onerror事件来判断,出错则更换image对象的src为默认图片的URL。 

<p>第一种情况:图片存在,正常显示
  
<img src="http://www.jb51.net/logo.gif"
onerror="javascript:this.src='http://www.jb51.net/logos.gif'" /></p>
<p>第二种情况:图片不存在,显示默认图片
  
<img src="http://www.jb51.net/logoddd.gif"
onerror="javascript:this.src='http://www.jb51.net/logos.gif'" /></p>

 注意:如果使用不当,在IE内核的浏览器下会造成死循环。比如:当【默认图片的url地址】也加载不成功(比如网速比较慢的时候)或不存在的话,就会反复的加载,最后造成堆栈溢出错误。

因此, 需要用下面两种方法解决:
a、更改 onerror 代码为其它处理方式或者确保 onerror 中的默认图片足够小,并且存在。
b、控制onerror事件只触发一次,需要增加这句话:this.onerror=null; 增加后如下:
1
<img src="图片的url地址" alt="图片XX" onerror="this.src='默认图片的url地址;this.onerror=null'"/>

下面是通过js的判断
用javascript判断指定图片文件是否存在: 
如判断<img src="http://www.jb51.net/logos.gif">这个图片地址是否存在. 
如果不存在,隔几秒重新探测此图片,如果地址有效则,提示地址有效 

<script type="text/javascript">
function IsExist(url)
{
  x = new ActiveXObject("Microsoft.XMLHTTP")
  x.open("HEAD",url,false)
  x.send()
  return x.status==200
}
alert(IsExist("http://www.jb51.net/logos.gif"));
</script>

图片存在则上面的返回true 

<SCRIPT language="javascript">
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.Open("GET""http://www.jb51.net/logos.gif", false);
xmlhttp.Send();
alert(xmlhttp.responseText);
</SCRIPT>

图片存在则返回GIF89aX 

<img src="http://www.jb51.net/logos2.gif" onerror="alert('该图片不存在!');">

因为图片不存在则返回该图片不存在!

 

补充:

down vote
accepted
You could use something like:

function imageExists(image_url){

    var http = new XMLHttpRequest();

    http.open('HEAD', image_url, false);
    http.send();

    return http.status != 404;

}
Obviously you could use jQuery/similar to perform your HTTP request.

$.get(image_url)
    .done(function() { 
        // Do something now you know the image exists.

    }).fail(function() { 
        // Image doesn't exist - do something else.

    })

 

原地址:http://www.jb51.net/article/8796.htm

posted @ 2017-01-18 16:01  侧耳倾听的世界  阅读(7204)  评论(0编辑  收藏  举报