Get full size of image in javascript/jquery

后端 未结 4 1770
甜味超标
甜味超标 2021-02-15 02:53

I have an image on page that has been resized to fit in a div, say, 400x300. How can I get the full size of the image (~4000x3000) in jQuery? .width() and .height() only seem to

4条回答
  •  伪装坚强ぢ
    2021-02-15 03:24

    Images have naturalWidth and naturalHeight properties that contain the actual, non-modified width and height of the image, i.e. the real dimensions of the image, not what CSS sets it to.

    One would still have to wait for the image to load though

    $('#idOfMyimg').on('load', function() {
        var height = this.naturalHeight,
            width  = this.naturalWidth;
    });
    

    Another option would be to create a new image with the same file as the source, and get the dimensions from that, as long as it's never added to the DOM, not external styles will affect it

    var img = new Image();
    
    img.onload = function() {
       var height = this.height,
           width  = this.width;
    }
    img.src = $('#idOfMyimg').attr('src');
    

    FIDDLE

提交回复
热议问题