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

前端 未结 29 2988
忘了有多久
忘了有多久 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 05:48

    Recently I had same issue for an error in the flex slider. The first image's height was set smaller due to the loading delay. I tried the following method for resolving that issue and it's worked.

    // create image with a reference id. Id shall be used for removing it from the dom later.
    var tempImg = $('');
    //If you want to get the height with respect to any specific width you set.
    //I used window width here.
    tempImg.css('width', window.innerWidth);  
    tempImg[0].onload = function () {
        $(this).css('height', 'auto').css('display', 'none');
        var imgHeight = $(this).height();
        // Remove it if you don't want this image anymore.
        $('#testImage').remove();
    }
    //append to body
    $('body').append(tempImg);
    //Set an image url. I am using an image which I got from google.
    tempImg[0].src ='http://aspo.org/wp-content/uploads/strips.jpg';
    

    This will give you the height with respect to the width you set rather than original width or Zero.

提交回复
热议问题