How do I get actual image width and height using jQuery?

前端 未结 5 1041
情书的邮戳
情书的邮戳 2020-11-30 05:49

On a page I have displayed 100 images, which have the width and height attribute changed. Image id is in a loop.

How do I get the original image size, inside this

5条回答
  •  时光取名叫无心
    2020-11-30 06:41

    The only way to get the original size is to restore it to its original state. You can do this pretty easily by cloning the image, then removing the height and width attributes to get the real values. You also have to then insert the changed image into the page or else it wont have a calculated height/width. You can do this easily in an offscreen div. Here's an example:

    http://jsbin.com/ocoto/edit

    The JS:

    // Copy the image, and insert it in an offscreen DIV
    aimgcopy = $('#myimg').clone();
    $('#store').append(aimgcopy);
    
    // Remove the height and width attributes
    aimgcopy.removeAttr('height');
    aimgcopy.removeAttr('width');
    
    // Now the image copy has its "original" height and width
    alert('Height: '+aimgcopy.height()+' Width: '+aimgcopy.width());
    

    The CSS:

      #store {  position: absolute;  left: -5000px; }
    

    The HTML:

      
      

提交回复
热议问题