jquery get image size

拟墨画扇 提交于 2019-11-29 10:59:30
Pekka 웃

I asked the same question recently and got a good answer: A new image element is created but not attached to the DOM. Its height and width are the original dimensions of the image.

Edit: I edited the answer to my question now as promised in the comments. Detection of the image size is now bound to the onload event of the image to guarantee reliable results.

If an element is hidden you can't get its size, if you want to get its width or height before showing it, you need to give a negative offset like

#your_image {left:-1000%;}

only then

$(this).width()

will return you the result.

The problem with using jQuery to get image size is that usually we use $().ready(function()); to exec our javascript, but at that point the page load, the image isn't loaded yet, so you need to wait for that to happen first. Once you're sure the image is loaded, and the image is visible, you can use $.width() and $.height() as normal.

One thing you might try as well if you're using a scripted language to generate your image sizes is to put the width and height attributes after reading the file and getting the size that way. Since you're making a gallery, you might consider resizing your images on the backend with imagemagick of gd for php. There is plenty of documentation online for those tools, so I won't get into it here.

sanris
$("#your_img").imagesLoaded(function(){<br>
alert( $(this).width() );<br>
alert( $(this).height() );<br>
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!