现代浏览器(包括IE9)为IMG元素提供了naturalWidth和naturalHeight属性来获取实际宽度与高度 ,代码如下:
var
nWidth = document.getElementById('example').naturalWidth,
nHeight = document.getElementById('example').naturalHeight;
在IE8及以前浏览器中并不支持naturalWidth和naturalHeight属性。为IE7,8采用new Image()的方式来获取width和height:
function getNatural (DOMelement) {
var img = new Image();
img.src = DOMelement.src;
return {width: img.width, height: img.height};
}
var
natural = getNatural(document.getElementById('example')),
nWidth = natural.width,
nHeight = natural.height;
为jQuery添加了两个方法:naturalWidth()和naturalHeight():
(function($){
var
props = ['Width', 'Height'],
prop;
while (prop = props.pop()) {
(function (natural, prop) {
$.fn[natural] = (natural in new Image()) ?
function () {
return this[0][natural];
} :
function () {
var
node = this[0],
img,
value;
if (node.tagName.toLowerCase() === 'img') {
img = new Image();
img.src = node.src,
value = img[prop];
}
return value;
};
}('natural' + prop, prop.toLowerCase()));
}
}(jQuery));
// 如何使用:
var
nWidth = $('img#example').naturalWidth(),
nHeight = $('img#example').naturalHeight();
扫码关注w3ctech微信公众号
nice!
<a href="www.09441.cn">呵呵</a>
共收到2条回复