Is there any way to read out the “naturalWidth” of an image with jquery?

前端 未结 8 2146
时光说笑
时光说笑 2020-12-05 10:59

I tried with something like this:

var Height = $(this).naturalHeight;

But it doesn\'t work. Is there any way to do that

greez

8条回答
  •  暖寄归人
    2020-12-05 11:08

    One way to get the dimensions of an image is to dynamically load a copy of the image using javascript and obtain it's dimensions:

    // preload the image
    var height, width = '';
    var img = new Image();
    var imgSrc = '/path/to/image.jpg';
    
    $(img).load(function () {
        alert('height: ' + img.height);
        alert('width: ' + img.width);
        // garbage collect img
        delete img;
    }).error(function () {
        // image couldnt be loaded
        alert('An error occurred and your image could not be loaded.  Please try again.');
    }).attr({ src: imgSrc });
    

提交回复
热议问题