JS获取图片的原始宽度和高度,兼容IE7,8
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;
作者:人参,每篇随笔皆原创(除非注明原作者的随笔),欢迎指正!