Get image size using jQuery

I have a list of images

<img src="001.jpg"> <img src="002.jpg"> <img src="003.jpg"> <img src="004.jpg"> <img src="005.jpg"> 

Each image has a width of 200 pixels, but the heights are different. Is there a way with jQuery to find and then set the height of each image after loading?

I plan to have dozens of images on one page and do not want to add the width and height attribute to each image tag.

I use the Masonry Plugin, and the images require the width and height attribute.

+4
source share
4 answers

I believe this will do what you want:

 $('img').each(function() { $(this).attr('height',$(this).height()); $(this).attr('width',$(this).width()); }); 

You probably also want to add the class="masonry" attribute for each img, and then make your $('img.masonry') selector.

+4
source

You can try:

 $('img').each( function(){ var height = $(this).height(); var width = $(this).width(); $(this).attr({'height': height, 'width': width}); }) 

Assuming that the height / width attributes should be set to the actual img height / width, and not scaled / resized in any way.

Literature:

+3
source

You can use the jQuery .height() and .width() methods as they return the calculated width and height. You should always include width and height attributes in your img tags, as some browsers will not display these images correctly without them.

+1
source

Of course, use the height method to get the size of the img tags.

http://api.jquery.com/height/

0
source

Source: https://habr.com/ru/post/1342928/


All Articles