標籤:客戶 new flow src hidden nts 固定 blog alt
如何擷取圖片的原始大小大小?
如下,當給 img 設定一個固定的大小時,要怎樣擷取圖片的原始大小呢?
#oImg{ width: 100px; height: 100px;}
<img src="images/test.jpg" id="oImg" alt="">
HTML5提供了一個新屬性 naturalWidth / naturalHeight 可以直接擷取圖片的原始寬高。這兩個屬性在Firefox/Chrome/Safari/Opera及IE9裡已經實現。
w = document.getElementByTagName("img").naturalWidth; h = document.getElementsByTagName("img").naturalHeight; console.log(w + ‘ ‘ + h);
列印出來的結果與原始大小相符。但有個前提是,必須在圖片完全下載到用戶端瀏覽器才能判斷。
如果是不支援的版本瀏覽器,那可以用傳統方法判斷,如下:
var oImg = document.getElementById("oImg"), w,h; if (oImg.naturalWidth) { // HTML5 browsers w = oImg.naturalWidth; h = oImg.naturalHeight; } else { // IE 6/7/8 var nImg = new Image(); nImg.src = oImg.src; nImg.onload = function () { w = nImg.width; h = nImg.height;
console.log(w + " " + h) } }
此時為什麼要加 onload 的原因是,圖片可能沒載入完成,導致圖片的 width 、height 無法擷取到。
還有下面一種情況:圖片外面有個盒子,且盒子display:none;
.imgbox{ width: 100px; height: 100px; display: none;}<div class="imgbox"> <img src="images/test.jpg" id="oImg" alt=""></div>
嫌建立 new Image() 麻煩,就想到另外一種方法。
var oImg = document.getElementById("oImg"), w,h; if (oImg.naturalWidth) { // HTML5 browsers w = oImg.naturalWidth; h = oImg.naturalHeight; } else { // IE 6/7/8 w = oImg.width; h = oImg.height; }console.log(w + " " + h)
但這種方法,在ie8 下是擷取不到 img width / height 的。此時,我們要對 imgbox 做下處理。
.imgbox{ width: 0; overflow: hidden;}
現在就可以相容 ie8 了。
js擷取圖片原始大小