图像加载不适用于 IE 8 或更低版本
Image load not working with IE 8 or lower
我的目标是检查图像是否已成功加载。它在现代浏览器中运行良好,但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');
}
}
有人有任何想法来解决这个问题吗?谢谢你!
在设置.src
值之前,您必须设置onload
处理程序。
在某些版本的 IE 中,如果图像位于浏览器缓存中,则在设置 .src
值时将立即触发 load 事件。 如果负载处理程序尚未到位,您将错过该事件。
此外,旧版本的 IE 不支持naturalWidth
和naturalHeight
,因此它们将始终未定义。 并且,您应该使用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';
如果映像损坏,则不会触发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);
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;
}
相关文章:
- 如何确定相对较新版本的IE的高度和宽度(IE8不喜欢从JavaScript设置这种样式吗?
- javascript网格未在IE 8及以上版本中显示
- 是否可以使用Javascript检测所有版本的IE?怎样
- 针对IE 8及以下版本
- 图像加载不适用于 IE 8 或更低版本
- IE版本检查停止工作
- 如果用户的浏览器早于以下版本,则显示一条消息:IE 10、Firefox 39、Chrome 39、Opera 8
- 使用less.js检测旧版本的ie,然后使用filter
- jsPDF在任何IE版本中显示iframe
- fadeIn动画无法在IE中工作(所有版本)
- 获取IE版本+将类添加到正文
- 在Facebook图形中,使用Javascript的IE(所有版本)不支持API调用跨浏览器调用
- 什么版本的IE支持安全性=“;受限制的“;iframes
- 使用JQuery和IE在悬停时高亮显示表行-所有版本
- 如何在旧 IE 版本中将捕获组与 String.split 一起使用
- 对 IE 8 及更低版本的 NVD3 支持
- 什么是 IE 版本的网络驱动程序.Capabilities.firefox().
- 旧版本IE上的Jquery问题
- 某些版本IE中的JavaScript重定向问题
- 旧版本IE中JSON对象的问题