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

前端 未结 29 2996
忘了有多久
忘了有多久 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: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()));
    }
    

提交回复
热议问题