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

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

    You can only really do this using a callback of the load event as the size of the image is not known until it has actually finished loading. Something like the code below...

    var imgTesting = new Image();
    
    function CreateDelegate(contextObject, delegateMethod)
    {
        return function()
        {
            return delegateMethod.apply(contextObject, arguments);
        }
    }
    
    function imgTesting_onload()
    {
        alert(this.width + " by " + this.height);
    }
    
    
    imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
    imgTesting.src = 'yourimage.jpg';
    

提交回复
热议问题