2012-11-19 63 views

回答

2

這很簡單,使用onerror事件。

我們可以簡單地在JavaScript中創建一個新圖像並將兩個事件附加到它上面 - onloadonerror。然後設置圖像src將使瀏覽器下載圖像,如果它是真實圖像則觸發onload事件,如果不是則爲onerror

var img = new Image(); 

// This URL will return an image an fire `onload` 
img.src = 'http://placekitten.com/300/300'; 

// Replace the line above with this one to load a fake/unavailable image, which will fire the `onerror` event. 
// img.src = 'http://mybrokenurl'; 

img.onload = function() { 
    document.body.appendChild(img); 
} 

img.onerror = function() { 
    alert('Error loading image'); 
}​ 

演示:http://jsfiddle.net/amustill/vSJ4F/