頁面中的img元素,想要獲取它的原始尺寸,以寬度為例,可能首先想到的是元素的innerWidth屬性,或者jQuery中的width()方法。如下:
<img id="img" src="1.jpg"> <script type="text/javascript"> var img = document.getElementById("img"); console.log(img.innerWidth); // 600 </script>
這樣貌似可以拿到圖片的尺寸。
但是如果給img元素增加了width屬性,比如圖片實際寬度是600,設置了width為400。這時候innerWidth為400,而不是600。顯然,用innerWidth獲取圖片原始尺寸是不靠譜的。
這是因為 innerWidth屬性獲取的是元素盒模型的實際渲染的寬度,而不是圖片的原始寬度。
<img id="img" src="1.jpg" width="400"> <script type="text/javascript"> var img = document.getElementById("img"); console.log(img.innerWidth); // 400 </script>
jQuery的width()方法在底層調用的是innerWidth屬性,所以width()方法獲取的寬度也不是圖片的原始寬度。
那么該怎么獲取img元素的原始寬度呢?
naturalWidth / naturalHeight
現代瀏覽器(包括IE9)為img元素提供了 naturalWidth 和 naturalHeight屬性來獲取圖片的實際寬度與高度 。如下:
var naturalWidth = document.getElementById('img').naturalWidth, naturalHeight = document.getElementById('img').naturalHeight;
naturalWidth / naturalHeight在各大瀏覽器中的兼容性如下:
所以,如果不考慮兼容至IE8的,可以放心使用naturalWidth / naturalHeight屬性了。
IE7/8中的兼容性實現:
在IE8及以前版本的瀏覽器並不支持naturalWidth和naturalHeight屬性。
在IE7/8中,我們可以采用new Image()的方式來獲取圖片的原始尺寸,如下:
function getNaturalSize (DomElement) { var img = new Image(); img.src = DomElement.src; return { width: img.width, height: img.height }; } // 使用 var natural = getNaturalSize (document.getElementById('img')), natureWidth = natural.width, natureHeight = natural.height; IE7+瀏覽器都能兼容的函數封裝: 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;
