我必须在120px×120px的div中显示用户的照片图像。 问题是图像可能具有不同的尺寸:调整图像的大小而不会损失纵横比
- 较小大中华区
- 不要广场。大问题。
有什么方法可以在方块内插入图像而不会损失长宽比?
注意:图像显示为background-image。我更喜欢CSS,但它可能是JavaScript或jQuery。
非常重要:需要是支持IE8。
我必须在120px×120px的div中显示用户的照片图像。 问题是图像可能具有不同的尺寸:调整图像的大小而不会损失纵横比
有什么方法可以在方块内插入图像而不会损失长宽比?
注意:图像显示为background-image。我更喜欢CSS,但它可能是JavaScript或jQuery。
非常重要:需要是支持IE8。
是的。你可以保持使用CSS规则的背景图像的长宽比:
background-size: cover;
background-size: contain;
更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/background-size
尝试使用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
}
});
你可能会考虑使用[**背景大小,填充工具**](https://github.com/louisremi/background-size-polyfill)为IE8 – Aziz