gpt4 book ai didi

javascript - 在不丢失宽高比的情况下调整图像大小

转载 作者:太空宇宙 更新时间:2023-11-03 19:38:29 25 4
gpt4 key购买 nike

我必须在 120 像素 x 120 像素的 div 中显示用户的照片图像。问题是图像可能有不同的尺寸:

  • 变小
  • 更大
  • 不要正方形。大问题。

有什么方法可以在不丢失纵横比的情况下在正方形内插入图片?

注意:图像显示为背景图像。我更喜欢 CSS,但它可以是 javascript 或 jquery。

非常重要:需要IE8支持

最佳答案

尝试使用 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/

关于javascript - 在不丢失宽高比的情况下调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36694652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com