2016-04-18 100 views
1

我必须在120px×120px的div中显示用户的照片图像。 问题是图像可能具有不同的尺寸:调整图像的大小而不会损失纵横比

  • 较小大中华区
  • 不要广场。大问题。

有什么方法可以在方块内插入图像而不会损失长宽比

注意:图像显示为background-image。我更喜欢CSS,但它可能是JavaScript或jQuery。

非常重要:需要是支持IE8

+1

你可能会考虑使用[**背景大小,填充工具**](https://github.com/louisremi/background-size-polyfill)为IE8 – Aziz

回答

-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/

+0

当你复制完整的代码,请链接源... http://stackoverflow.com/questions/1143517/jquery-resizing-image –

+0

这是为背景图像? – jpussacq

+0

对不起,只适用于使用img标签的实际图片。 – vviston

相关问题