Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/425.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 图像加载不适用于IE 8或更低版本_Javascript_Image_Internet Explorer - Fatal编程技术网

Javascript 图像加载不适用于IE 8或更低版本

Javascript 图像加载不适用于IE 8或更低版本,javascript,image,internet-explorer,Javascript,Image,Internet Explorer,我的目标是检查图像是否已成功加载。它在现代浏览器中运行良好,但在IE8或IE7中这是一个可怕的问题。下面是一个示例代码: var img = new Image(), url = 'http://something.com/images/something.gif'; $(img).attr('src', url).load(function() { if (!this.complete || typeof this.naturalWidth == "undef

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

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');
        }
    } 

有人有办法解决这个问题吗?谢谢你

如果图像被破坏,则不会触发
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);

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

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

另外,
naturalWidth
naturalHeight
在旧版本的IE中不受支持,因此它们总是未定义。并且,您应该使用
onerror
onabort
来捕获错误条件

没有必要为此使用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';

谢谢,但我想知道为什么在Chrome和Firefox中工作得很好,当图像成功加载时我会得到提醒。假设图像正常,您还有其他建议吗?欢迎来到浏览器不一致的现实世界。处理这些问题。在这种情况下,如果图像已经加载,它将再次加载还是从缓存加载?如果指定的URL与以前加载的URL相同,浏览器将从缓存加载它。这就是缓存的重点。
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;
}