How to get image size (height & width) using JavaScript?

前端 未结 29 3757
忘了有多久
忘了有多久 2020-11-21 05:23

Are there any JavaScript or jQuery APIs or methods to get the dimensions of an image on the page?

29条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 06:08

    I think an update to these answers is useful because one of the best-voted replies suggests using clientWidth and clientHeight, which I think is now obsolete.

    I have done some experiments with HTML5, to see which values actually get returned.

    First of all, I used a program called Dash to get an overview of the image API. It states that height and width are the rendered height/width of the image and that naturalHeight and naturalWidth are the intrinsic height/width of the image (and are HTML5 only).

    I used an image of a beautiful butterfly, from a file with height 300 and width 400. And this Javascript:

    var img = document.getElementById("img1");
    
    console.log(img.height,           img.width);
    console.log(img.naturalHeight,    img.naturalWidth);
    console.log($("#img1").height(),  $("#img1").width());
    

    Then I used this HTML, with inline CSS for the height and width.

    
    

    Results:

    /*Image Element*/ height == 300         width == 400
               naturalHeight == 300  naturalWidth == 400
    /*Jquery*/      height() == 120       width() == 150
    
    /*Actual Rendered size*/    120                  150
    

    I then changed the HTML to the following:

    
    

    i.e. using height and width attributes rather than inline styles

    Results:

    /*Image Element*/ height ==  90         width == 115
               naturalHeight == 300  naturalWidth == 400
    /*Jquery*/      height() ==  90       width() == 115
    
    /*Actual Rendered size*/     90                  115
    

    I then changed the HTML to the following:

    
    

    i.e. using both attributes and CSS, to see which takes precedence.

    Results:

    /*Image Element*/ height ==  90         width == 115
               naturalHeight == 300  naturalWidth == 400
    /*Jquery*/      height() == 120       width() == 150
    
    /*Actual Rendered size*/    120                  150
    

提交回复
热议问题