首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

兼容IE,firefox,chrome,safari预加载图片height跟width获取

2012-11-22 
兼容IE,firefox,chrome,safari预加载图片height和width获取var imgnew Image()?img.srcxxxx图片路径

兼容IE,firefox,chrome,safari预加载图片height和width获取

var img=new Image();?
img.src="xxxx图片路径";?
然后alert(img.height);?
这种写法在chrome上就不适用了,在chrome中弹出0.?
为了修正这种异常可以采用下面的写法?

function loadImage(url) {?
??? var img = new Image();?
??? img.src = url;?
??? if (img.complete) {?
??????? alert(img.width);?
??????? return;?
??? }?

??? img.onload = function () {?
??????? callback.call(img);?
?????????? alert(this.height);?
??? };?
};?
这种写法就可以解决这个这一问题了。?
jquery写法?
$("img").load(function(){?
if (this.complete||this.readyState=="complete") {?
??????? $(this).css({"margin-left":(120-this.width)/2,"margin-top":(80-this.height)/2});?
??????? return;?
??? }?
})

热点排行