簡體   English   中英

確定圖像跨瀏覽器的原始大小?

[英]Determine original size of image cross browser?

是否有一種可靠的,獨立於框架的方法來確定客戶端調整大小的<img src='xyz.jpg'>的物理尺寸?

你有2個選擇:

選項1:

刪除widthheight屬性並讀取offsetWidthoffsetHeight

選項2:

創建一個JavaScript Image對象,設置src ,並讀取widthheight (您甚至不必將其添加到頁面來執行此操作)。

function getImgSize(imgSrc) {
    var newImg = new Image();

    newImg.onload = function() {
      var height = newImg.height;
      var width = newImg.width;
      alert ('The image size is '+width+'*'+height);
    }

    newImg.src = imgSrc; // this must be done AFTER setting onload
}

由Pekka編輯 :根據評論中的約定,我將函數更改為在圖像的'onload'事件上運行。 否則,對於大圖像, heightwidth將不會返回任何內容,因為圖像尚未加載。

圖像(至少在Firefox上)具有naturalWidth / height屬性,因此您可以使用img.naturalWidth來獲取原始寬度

var img = document.getElementsByTagName("img")[0];
img.onload=function(){
    console.log("Width",img.naturalWidth);
    console.log("Height",img.naturalHeight);
}

資源

您可以將圖像預加載到javascript Image對象中,然后檢查該對象的width和height屬性。

/* Function to return the DOM object's in crossbrowser style */
function widthCrossBrowser(element) {
    /* element - DOM element */

    /* For FireFox & IE */
    if(     element.width != undefined && element.width != '' && element.width != 0){
        this.width  =   element.width;
    }
    /* For FireFox & IE */
    else if(element.clientWidth != undefined && element.clientWidth != '' && element.clientWidth != 0){
        this.width  =   element.clientWidth;
    }
    /* For Chrome * FireFox */
    else if(element.naturalWidth != undefined && element.naturalWidth != '' && element.naturalWidth != 0){
        this.width  =   element.naturalWidth;
    }
    /* For FireFox & IE */
    else if(element.offsetWidth != undefined && element.offsetWidth != '' && element.offsetWidth != 0){
        this.width  =   element.offsetWidth;
    }       
        /*
            console.info(' widthWidth width:',      element.width);
            console.info(' clntWidth clientWidth:', element.clientWidth);
            console.info(' natWidth naturalWidth:', element.naturalWidth);
            console.info(' offstWidth offsetWidth:',element.offsetWidth);       
            console.info(' parseInt(this.width):',parseInt(this.width));
        */
    return parseInt(this.width);

}   

var elementWidth    = widthCrossBrowser(element);

只是改變一點Gabriel的第二個選項,更容易使用:

function getImgSize(imgSrc, callback) {
    var newImg = new Image();

    newImg.onload = function () {
        if (callback != undefined)
            callback({width: newImg.width, height: newImg.height})
    }

    newImg.src = imgSrc;
}

HTML:

<img id="_temp_circlePic" src="http://localhost/myimage.png" 
style="width: 100%; height:100%">

示例電話:

getImgSize($("#_temp_circlePic").attr("src"), function (imgSize) {
    // do what you want with the image's size.
    var ratio = imgSize.height / $("#_temp_circlePic").height();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM