我的目的是检查图像是否已成功加载。它在现代浏览器中运行良好,但在 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');
}
}
有人有解决这个问题的想法吗?提前致谢!
你必须设置onload
在设置之前处理程序.src
价值。
在某些版本的 IE 中,如果图像在浏览器缓存中,则加载事件将立即被触发。.src
值已设置。如果您的负载处理程序尚未就位,您将错过该事件。
Also, naturalWidth
and naturalHeight
旧版本的 IE 不支持,因此它们始终是未定义的。而且,你应该使用onerror
and 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';
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)