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

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

    var imgSrc, imgW, imgH;
    function myFunction(image){
        var img = new Image();
        img.src = image;
        img.onload = function() {   
            return {
                src:image,
                width:this.width,
                height:this.height};
            }
        return img;
    }
    var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
        //Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
    x.addEventListener('load',function(){
        imgSrc = x.src;
        imgW = x.width;
        imgH = x.height;
    });
    x.addEventListener('load',function(){
        console.log(imgW+'x'+imgH);//276x110
    });
    console.log(imgW);//undefined.
    console.log(imgH);//undefined.
    console.log(imgSrc);//undefined.
    

    This is my method, hope this helpful. :)

提交回复
热议问题