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

前端 未结 29 2993
忘了有多久
忘了有多久 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:09
    var img = document.getElementById("img_id");
    alert( img.height + " ;; " + img .width + " ;; " + img .naturalHeight + " ;; " + img .clientHeight + " ;; " + img.offsetHeight + " ;; " + img.scrollHeight + " ;; " + img.clientWidth + " ;; " + img.offsetWidth + " ;; " + img.scrollWidth )
    //But all invalid in Baidu browser  360 browser ...
    
    0 讨论(0)
  • 2020-11-21 06:10

    Assuming, we want to get image dimensions of <img id="an-img" src"...">

    // Query after all the elements on the page have loaded.
    // Or, use `onload` on a particular element to check if it is loaded.
    document.addEventListener('DOMContentLoaded', function () {
      var el = document.getElementById("an-img");
    
      console.log({
        "naturalWidth": el.naturalWidth, // Only on HTMLImageElement
        "naturalHeight": el.naturalHeight, // Only on HTMLImageElement
        "offsetWidth": el.offsetWidth,
        "offsetHeight": el.offsetHeight
      });
    
    

    Natural Dimensions

    el.naturalWidth and el.naturalHeight will get us the natural dimensions, the dimensions of the image file.

    Layout Dimensions

    el.offsetWidth and el.offsetHeight will get us the dimensions at which the element is rendered on the document.

    0 讨论(0)
  • 2020-11-21 06:10

    Nicky De Maeyer asked after a background picture; I simply get it from the css and replace the "url()":

    var div = $('#my-bg-div');
    var url = div.css('background-image').replace(/^url\(\'?(.*)\'?\)$/, '$1');
    var img = new Image();
    img.src = url;
    console.log('img:', img.width + 'x' + img.height); // zero, image not yet loaded
    console.log('div:', div.width() + 'x' + div.height());
    img.onload = function() {
      console.log('img:', img.width + 'x' + img.height, (img.width/div.width()));
    }
    
    0 讨论(0)
  • 2020-11-21 06:12

    This answer was exactly what I was looking for (in jQuery):

    var imageNaturalWidth = $('image-selector').prop('naturalWidth');
    var imageNaturalHeight = $('image-selector').prop('naturalHeight');
    
    0 讨论(0)
  • 2020-11-21 06:12

    JQuery Answer:

    $height = $('#image_id').height();
    $width  = $('#image_id').width();
    
    0 讨论(0)
提交回复
热议问题