jQuery jQuery更改图像高度保持纵横比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15339991/
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 change image height keep aspect ratio
提问by Doidgey
So i have a gallery where most my images are currently controlled 100% by CSS. However, in setting min-height: 100%; on my images, i cause some to stretch. I don't have too many problematic photos, but it's out of my control what the user will upload.
所以我有一个画廊,其中我的大多数图像目前由 CSS 100% 控制。但是,在设置 min-height: 100%; 在我的图像上,我导致一些拉伸。我没有太多有问题的照片,但用户上传什么是我无法控制的。
Is there anyway with jQuery i can get image height and check if it's meeting a requirement, and if not, somehow increase the image width in order to meet the height requirement but keep things all in ratio? So i therefore avoid causing any distortion but keep the gallery neat by having divs without gaps.
无论如何,jQuery 我可以获取图像高度并检查它是否满足要求,如果没有,以某种方式增加图像宽度以满足高度要求但保持所有比例?因此,我避免造成任何失真,但通过让 div 没有间隙来保持画廊整洁。
Note: The image provided is what happens when i remove my min-height: 100%;
so that you can see my issue.
注意:提供的图像是当我删除我min-height: 100%;
以便您可以看到我的问题时发生的情况。
Update - - - - -
更新 - - - - -
I found a solution that seems to work ok for the moment, it might not be the best attempt but i found another answer that helped me:How to resize images proportionally / keeping the aspect ratio?
我找到了一个目前似乎工作正常的解决方案,它可能不是最好的尝试,但我找到了另一个帮助我的答案:如何按比例调整图像大小/保持纵横比?
I simply tweaked the code ever so slightly, now if an image doesn't meet the minHeight
required it will resize the image in proportion so until the minHeight
is then reached. Seems work fine for me in testing.
我只是稍微调整了代码,现在如果图像不符合minHeight
要求,它将按比例调整图像大小,直到minHeight
达到。在测试中对我来说似乎很好。
**Update Final ********* After playing around i took a small snippit from the thumb script, just the part where it absolutely positions the images within the container.
** 更新最终版本 ********* 在玩完之后,我从拇指脚本中取出了一个小片段,只是它在容器中绝对定位图像的部分。
$(window).load(function() {
$('.thumbnail img').each(function() {
var maxWidth = 320; // Max width for the image
var minHeight = 270; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if(height < minHeight){
ratio = minHeight / height; // get ratio for scaling image
$(this).css("height", minHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
var $img = $(this),
css = {
position: 'absolute',
marginLeft: '-' + ( parseInt( $img.css('width') ) / 2 ) + 'px',
left: '50%',
top: '50%',
marginTop: '-' + ( parseInt( $img.css('height') ) / 2 ) + 'px'
};
$img.css( css );
});
});
});
This loops through all my thumbnails, resizes them accordingly. So if the minimum height is not met, the image will be scaled up until the height fits my thumbnail container. Then the bottom part will take take each image, absolutely position it, and take the width and height and divide by 2, in order to work out how much to minus off on the margins to center the image. I'm still tweaking this, but seems to work well for me at the moment. I hope this helps someone else.
这会遍历我所有的缩略图,并相应地调整它们的大小。因此,如果不满足最小高度,图像将被放大,直到高度适合我的缩略图容器。然后底部将获取每个图像,绝对定位它,并获取宽度和高度并除以 2,以便计算出在边缘上减去多少以使图像居中。我仍在调整这个,但目前似乎对我来说效果很好。我希望这对其他人有帮助。
Alternatively
或者
Anyone with a similar issue i found this: http://joanpiedra.com/jquery/thumbs/I had begun writing my own to do exactly this, but im going to look into how well this works and adapt it as needed.
任何有类似问题的人我都发现了这个:http: //joanpiedra.com/jquery/thumbs/我已经开始写我自己的来做到这一点,但我将研究它的工作情况并根据需要进行调整。
采纳答案by Doidgey
I found a solution that seems to work ok for the moment, it might not be the best attempt but i found another answer that helped me:How to resize images proportionally / keeping the aspect ratio?
我找到了一个目前似乎工作正常的解决方案,它可能不是最好的尝试,但我找到了另一个帮助我的答案:如何按比例调整图像大小/保持纵横比?
Updated question with my findings
用我的发现更新了问题
$(window).load(function() {
$('.image-gallery-item-image-link img').each(function() {
var maxWidth = 320; // Max width for the image
var minHeight = 270; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if(height < minHeight){
ratio = minHeight / height; // get ratio for scaling image
$(this).css("height", minHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
var $img = $(this),
css = {
position: 'absolute',
marginLeft: '-' + ( parseInt( $img.css('width') ) / 2 ) + 'px',
left: '50%',
top: '50%',
marginTop: '-' + ( parseInt( $img.css('height') ) / 2 ) + 'px'
};
$img.css( css );
});
});
回答by Todd
well, if keeping the entire picture visible isn't necessary(e.g. thumbnails in a gallery), you could accomplish this with css only. it seems you have landscape type photos. html
好吧,如果不需要保持整个图片可见(例如画廊中的缩略图),您可以仅使用 css 来完成此操作。看来你有风景类型的照片。html
<div class="img-container">
<img src="path/to/img.png" alt="">
</div>
css:
css:
div > img {
background-repeat: no-repeat;
background-position: center center;
background-attachment: fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
width:100%;
height:100%;
}
}
jquery:
$(document).ready(function(){
$(".imgcontainer > img").each(function(){
var thisimg = "url("+$(this).attr('src')+")";
$(this).css({'background-image': thisimg });
$(this).attr('src', '');
});
});
回答by codeVerine
Whose aspect ratio you are talking about ? aspect ratio of your gallery or the aspect ratio of the image ? You can't keep an image in correct aspect ratio by changing one dimension only (here height). In order to keep aspect ratio, you must change both the height and width of the image. Any way if you want try this :
你说的长宽比是谁的?您画廊的纵横比或图像的纵横比?您无法通过仅更改一个维度(此处为高度)来保持图像的正确纵横比。为了保持纵横比,您必须同时更改图像的高度和宽度。无论如何,如果你想试试这个:
var img = document.getElementById('imageid');
var width = img.clientWidth;
var height = img.clientHeight;
if(width >height)
$(img).attr('style',"width=100%");
else
$(img).attr('style',"height=100%");
What I am trying to do is that, set the css of the largest dimension to 100%. It'll do the trick.
我想要做的是,将最大尺寸的 css 设置为 100%。它会做的伎俩。
回答by Todd
So, I realize this question asked a while ago. But I've since found a sweet css only way to maintain the aspect ratio of an element, fluidly. Try it out:
所以,我意识到这个问题不久前被问到了。但从那以后,我找到了一种甜蜜的 css 唯一方法来流畅地保持元素的纵横比。试试看:
#targetElement {
max-width: 100%;
}
#targetElement:after {
content: '';
width: 100%;
padding-bottom: <aspect-ratio>%; // where (height / width)*100 = <aspect-ratio>
}
Yeah, so I use this trick all the time now, and it's definitely more performant and less verbose than using javascript, or even less efficient, JQuery. Hope this helps somebody somewhere! If you're a LESS person, I have a mixin Gist on Github that does this -- that's how often I use it! It lives here: Sweet AR trick.
是的,所以我现在一直在使用这个技巧,它肯定比使用 javascript 或者效率更低的 JQuery 性能更高,而且更简洁。希望这可以帮助某人某处!如果你是一个 LESS 人,我在 Github 上有一个 mixin Gist 可以做到这一点——这就是我使用它的频率!它住在这里:甜蜜的 AR 技巧。