Sin*_*nal 6 javascript internet-explorer image
我的目标是检查图像是否已成功加载.它在现代浏览器中运行良好,但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');
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都有任何想法解决这个问题?谢谢你的推荐!
jfr*_*d00 13
您必须onload
在设置.src
值之前设置处理程序.
在某些版本的IE中,如果图像位于浏览器缓存中,则在设置.src
值时将立即触发load事件.如果您的装载处理程序尚未到位,您将错过该事件.
此外,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';
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7543 次 |
最近记录: |