【问题标题】: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


【解决方案1】:

是的。您可以使用 CSS 规则保持背景图像的纵横比:

background-size: cover;
background-size: contain;

更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

【讨论】:

  • IE8不支持这个
  • IE8 不支持 :-(
【解决方案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/

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 2010-12-03
  • 2014-03-13
  • 1970-01-01
  • 2013-05-12
  • 2013-02-24
  • 1970-01-01
相关资源
最近更新 更多