利用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