js擷取圖片原始大小

來源:互聯網
上載者:User

標籤:客戶   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擷取圖片原始大小

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.