naturalWidth和naturalHeight 可以直接获取img的原始宽高,而innerHight,innerWith只是获取图片所占容器盒子的宽高。
// 封装
function getNaturalSize (DomElement) {
var natureSize = {};
if(window.naturalWidth && window.naturalHeight) {
natureSize.width = DomElement.naturalWidth;
natureSizeheight = DomElement.naturalHeight;
} else {
var img = new Image();
img.src = DomElement.src;
natureSize.width = img.width;
natureSizeheight = img.height;
}
return natureSize;
}
// 使用
var natural = getNaturalSize (document.getElementById('img')),
natureWidth = natural.width,
natureHeight = natural.height;