【发布时间】:2013-02-26 17:06:02
【问题描述】:
所以我有一个画廊,我的大多数图像目前 100% 由 CSS 控制。但是,在设置 min-height: 100%;在我的图像上,我造成一些拉伸。我没有太多有问题的照片,但我无法控制用户上传的内容。
无论如何,我可以使用 jQuery 获取图像高度并检查它是否满足要求,如果没有,以某种方式增加图像宽度以满足高度要求但保持所有比例?所以我因此避免造成任何失真,但通过让 div 没有间隙来保持画廊整洁。
注意:提供的图片是我删除 min-height: 100%; 时发生的情况,以便您可以看到我的问题。
更新 - - - - -
我找到了一个目前似乎可以正常工作的解决方案,这可能不是最好的尝试,但我找到了另一个对我有帮助的答案: How to resize images proportionally / keeping the aspect ratio?
我只是稍微调整了代码,现在如果图像不符合minHeight 要求,它将按比例调整图像大小,直到达到minHeight。在测试中对我来说似乎工作正常。
**更新最终版 ********* 在玩了之后,我从拇指脚本中提取了一个小片段,只是它在容器中绝对定位图像的部分。
$(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 );
});
});
这会遍历我所有的缩略图,并相应地调整它们的大小。因此,如果不满足最小高度,图像将被放大,直到高度适合我的缩略图容器。然后底部将拍摄每张图像,绝对定位它,并将宽度和高度除以 2,以便计算出在边缘减去多少以使图像居中。我仍在调整它,但目前似乎对我来说效果很好。我希望这对其他人有帮助。
或者
任何有类似问题的人我都发现了这个:http://joanpiedra.com/jquery/thumbs/ 我已经开始编写自己的代码来做到这一点,但我将研究它的工作情况并根据需要进行调整。
【问题讨论】:
标签: javascript jquery