jquery 获取图片大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2038075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery get image size
提问by ngreenwood6
I am creating a photo gallery using jquery. I am taking and resizing the images on load to create thumbnails. I want to get the original value of the image's size so that later on I can take it back to its original size. Anyone know how to do this? I have the following code:
我正在使用 jquery 创建一个照片库。我正在加载并调整图像大小以创建缩略图。我想获得图像大小的原始值,以便稍后我可以将其恢复到原始大小。有人知道怎么做吗?我有以下代码:
obj.find("img").each(function(){
});
This loops through all the images within the container div. I then tried to do:
这会循环遍历容器 div 中的所有图像。然后我尝试做:
$(this).width(); //didnt work
this.width; //didnt work
any ideas?
有任何想法吗?
回答by Pekka
I asked the same questionrecently 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.
我最近问了同样的问题,得到了一个很好的答案:创建了一个新的图像元素,但没有附加到 DOM。它的高度和宽度是图像的原始尺寸。
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.
编辑:我现在按照评论中的承诺编辑了我的问题的答案。图像大小的检测现在绑定到onload
图像的事件以保证可靠的结果。
回答by Sinan
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%;}
#your_image {left:-1000%;}
only then
只有那时
$(this).width()
$(this).width()
will return you the result.
将返回结果。
回答by Aaron
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.
使用 jQuery 获取图像大小的问题是我们通常使用 $().ready(function()); 执行我们的 javascript,但此时页面加载,图像尚未加载,因此您需要先等待它发生。一旦确定图像已加载并且图像可见,您就可以正常使用 $.width() 和 $.height() 。
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.
如果您使用脚本语言生成图像大小,您也可以尝试的一件事是在读取文件并以这种方式获取大小后放置宽度和高度属性。由于您正在制作图库,您可能会考虑使用 gd for php 的 imagemagick 在后端调整图像大小。这些工具的在线文档有很多,所以我不会在这里介绍。
回答by sanris
$("#your_img").imagesLoaded(function(){<br>
alert( $(this).width() );<br>
alert( $(this).height() );<br>
});