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

前端 未结 29 3102
忘了有多久
忘了有多久 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:02

    ok guys, i think i improved the source code to be able to let the image load before trying to find out its properties, otherwise it will display '0 * 0', because the next statement would have been called before the file was loaded into the browser. Requires jquery...

    function getImgSize(imgSrc){
        var newImg = new Image();
        newImg.src = imgSrc;
        var height = newImg.height;
        var width = newImg.width;
        p = $(newImg).ready(function(){
            return {width: newImg.width, height: newImg.height};
        });
        alert (p[0]['width']+" "+p[0]['height']);
    }
    

提交回复
热议问题