使用 Jquery 获取图像大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5240532/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:47:59  来源:igfitidea点击:

Get image size with Jquery

jqueryheightwidth

提问by Ryan

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 is 200px wide but the heights are different. Is there a way with Jquery to find, and then set the height of each image after they load?

每张图像的宽度为 200 像素,但高度不同。有没有办法用 Jquery 来查找,然后在加载后设置每个图像的高度?

I plan on having dozens of images on a single page and don't want to add the width and height attribute to every single image tag.

我计划在一个页面上放置数十张图片,并且不想为每个单独的图片标签添加宽度和高度属性。

I am using the Masonry Plugin and it requires a width and height attribute for images.

我正在使用 Masonry 插件,它需要图像的宽度和高度属性。

采纳答案by Chris W.

I believe this will do what you want:

我相信这会做你想做的:

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

You will probably also want to add a class="masonry"attribute to each img as well and then make your selector $('img.masonry').

您可能还想为class="masonry"每个 img添加一个属性,然后制作您的选择器$('img.masonry')

回答by David says reinstate Monica

You could try:

你可以试试:

$('img').each(
    function(){
        var height = $(this).height();
        var width = $(this).width();

        $(this).attr({'height': height, 'width': width});
    })

Assuming that you want the height/widthattributes to be set to the img's actual height/width, rather than scaled/modified in some manner.

假设您希望将height/width属性设置为img的实际高度/宽度,而不是以某种方式缩放/修改。

References:

参考:

回答by Chris

You could use the jQuery .height()and .width()methods, as these return the computed width and height. You should always include the width and height attributes in your img tags however, as some browsers will not render these images correctly without them.

您可以使用 jQuery.height().width()方法,因为它们返回计算出的宽度和高度。但是,您应该始终在 img 标签中包含 width 和 height 属性,因为如果没有它们,某些浏览器将无法正确呈现这些图像。

回答by andypaxo

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

当然,使用 height 方法来获取 img 标签的大小。

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

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