【问题标题】:Resize an image without losing aspect ratio在不丢失纵横比的情况下调整图像大小
【发布时间】:2016-08-10 05:32:13
【问题描述】:
我必须在 120 x 120 像素的 div 中显示用户的照片图像。
问题是图像可能有不同的大小:
有没有办法在正方形内插入图片不丢失纵横比?
注意:图像显示为背景图像。我更喜欢 CSS,但它可以是 javascript 或 jquery。
非常重要:需要IE8支持。
【问题讨论】:
标签:
javascript
jquery
html
css
internet-explorer-8
【解决方案2】:
尝试使用 jQuery。您可以在保留纵横比的同时定义图片所需的高度和宽度。
检查这个例子。
$(document).ready(function() {
$('.story-small img').each(function() {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // 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
// Check if the current width is larger than the max
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 > maxHeight){
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
});
来源:http://ericjuden.com/2009/07/jquery-image-resize/