6

我的目标是检查图像是否已成功加载。它在现代浏览器中运行良好,但 IE8 或 7 这是一个可怕的问题。这是一个示例代码:

var img = new Image(),
    url = 'http://something.com/images/something.gif';

    $(img).attr('src', url).load(function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            alert('broken image!');
        } 
        else {
            alert('successfully loaded');
        }
    } 

任何人都知道解决这个问题吗?提前感谢!

4

3 回答 3

13

您必须onload在设置值之前设置处理程序.src

.src在某些版本的 IE 中,如果图像在浏览器缓存中,则在设置值时会立即触发 load 事件。如果您的负载处理程序尚未到位,您将错过该事件。

此外,旧版本的 IE 不支持naturalWidth并且naturalHeight它们将始终未定义。而且,您应该使用onerrorandonabort来捕获错误情况。

没有必要为此使用 jQuery。你可以这样做:

var img = new Image(),

img.onload = function() {
    alert("loaded successfully");
}
img.onerror = img.onabort = function() {
    alert("broken image");
}
// only set .src AFTER event handlers are in place
img.src = 'http://something.com/images/something.gif';
于 2012-08-17T05:12:29.530 回答
3

如果图像损坏,则onload不会触发onerror事件,而是触发事件。所以你需要这样做:

var img = new Image(),
url = 'http://something.com/images/something.gif';

img.onload = function() {
  alert('successfully loaded');
};

img.onerror = function() {
  alert('broken image!');
};

$(img).attr('src', url);

或者使用 jQuery:

$(img).load(function() {
  alert('successfully loaded');
}).error(function() {
  alert('broken image!');
}).attr('src', url);
于 2012-08-17T05:07:18.130 回答
1
var url="http://something.com/images/something.gif",
    img=new Image;
img.onload=img.onerror=function(ev){
  if(ev.type=="load")alert("successfully loaded");
  else if(ev.type=="error")alert("error loading");
}
img.src=url;
// If image is cached then no `onload` or `onerror` can occur.
if(img.complete){
  alert("successfully loaded");
  img.onload=img.onerror=null;
}
于 2012-08-17T05:15:45.787 回答