jQuery调整大小以保持宽高比

13

我该如何在jQuery中调整图像大小以保持一致的长宽比?例如设置最大高度并使宽度正确调整。谢谢。

5个回答

19

这是一个可能会做你想要的事情的有用函数:

jQuery.fn.fitToParent = function()
{
    this.each(function()
    {
        var width  = $(this).width();
        var height = $(this).height();
        var parentWidth  = $(this).parent().width();
        var parentHeight = $(this).parent().height();

        if(width/parentWidth < height/parentHeight) {
            newWidth  = parentWidth;
            newHeight = newWidth/width*height;
        }
        else {
            newHeight = parentHeight;
            newWidth  = newHeight/height*width;
        }
        var margin_top  = (parentHeight - newHeight) / 2;
        var margin_left = (parentWidth  - newWidth ) / 2;

        $(this).css({'margin-top' :margin_top  + 'px',
                     'margin-left':margin_left + 'px',
                     'height'     :newHeight   + 'px',
                     'width'      :newWidth    + 'px'});
    });
};

基本上,它会抓取一个元素,将其居中放置在父级内,然后拉伸其大小以适应整个父级,使得父级的背景不可见,同时保持其宽高比。

但是,这也可能不是您想要做的事情。


2
谢谢,这真是帮了我大忙! - sowasred2012
这有时会导致newWidth或newHeight大于相应的父级尺寸。我建议使用以下代码:https://dev59.com/i3VD5IYBdhLWcg3wBWzd#115492 - Jason Axelson
1
@JasonAxelson:这正是我回答的重点。该代码确保图像的两个维度都大于或等于父级的维度。这旨在覆盖,而不是填充。 - Eric

15
你可以手动计算,例如:
function GetWidth(newHeight,orginalWidth,originalHeight)
{
if(currentHeight == 0)return newHeight;
var aspectRatio = currentWidth / currentHeight;
return newHeight * aspectRatio;
}

请确保使用原始的图像值,否则它会随着时间的推移而降低质量。

编辑:示例jQuery版本(未经测试)

jQuery.fn.resizeHeightMaintainRatio = function(newHeight){
    var aspectRatio = $(this).data('aspectRatio');
    if (aspectRatio == undefined) {
        aspectRatio = $(this).width() / $(this).height();
        $(this).data('aspectRatio', aspectRatio);
    }
    $(this).height(newHeight); 
    $(this).width(parseInt(newHeight * aspectRatio));
}

请解释一下您所说的“最大值”。有max width/height css属性,这不是您要找的吗? - Paul
谢谢。第二个例子接近我想要的,但是这个例子不起作用。据我所知,问题之一是更改宽度或高度应该由css()函数设置。我尝试了那样做,但是这个例子仍然不起作用。那是因为aspectRatio没有设置吗? - usertest
jQuery.fn.resizeHeightMaintainRatio = function(newHeight){ 如果(this.aspectRatio == undefined) this.aspectRatio = parseInt($(this).css("width") / $(this).css("height")); $(this).css("height",newHeight); $(this).css("width",newHeight * this.aspectRatio); } - usertest
@Paul,与其使用parseInt,使用parseFloat可能会获得更好的结果。演示在这里,http://jsfiddle.net/nazmul2011/sqj5m/1/。 - Nazmul
嗯...好吧,你不需要使用parseFloat,因为该值已经是浮点数了,但我不确定为什么要使用parseInt。我认为它应该放在最终命令中,以防止非整数值被用作尺寸,而并非所有浏览器都支持这种情况。 - Paul
显示剩余2条评论

7

使用JQueryUI可调整大小

$("#some_image").resizable({ aspectRatio:true, maxHeight:300 });

aspectRatio: true -> 保持原始宽高比


1
是的,但如果您尚未使用UI,则调用此操作会产生很多开销。 - Paul
当然,他可能正在尝试复制可调整大小插件的功能...顺便说一下,调用 resizeable 将会做更多的事情,而不仅仅是调整图像的大小。 - Paul
在我看来,如果你只使用了一个 API 的 1%,而这个 API 可以用 10 行代码替代,那么我认为你不应该使用这个 API。(特别是 Web API)同时,在这种情况下,你需要评估整个项目,以确保你不会逐步重写已经存在的东西。 - Paul
@Paul 我建立了一个可调整大小和可拖动的库 - 有很多边缘情况,这个库大约150行长,花了我大约六个月的时间来完善。最近我转换到了jquery ui - 它更强大,开箱即用,处理边缘情况,并具有添加我库所擅长的所有功能的钩子。它确实大约是原来的十倍,但仍然只是页面上最大图像大小的一小部分。 - Trass Vasston
@TrassVasston,请再次阅读原帖——它没有提到允许用户调整任何内容。我从不建议任何独立开发者尝试自己解决这样的通用问题,除非这是他们想做的全部。顺便说一句,jQuery UI有点过时了,它的更新频率不高,也没有看到多少HTML5/CSS3增强功能。我对它最大的问题是,与jQuery不同,它与“主题”紧密耦合,这使得将功能放入其中变得很麻烦,并且它与其他CSS框架不兼容。现在是推出继任者的完美时机。 - Paul

1

哎呀,这个世界上有太多的复制粘贴者了!我也想知道这个问题,但我看到的都是无尽的缩放宽度或高度的例子...谁会想要另一个溢出呢?!

  • 调整宽度和高度而无需循环
  • 不超过图像的原始尺寸
  • 使用正确的数学方法,即宽度/纵横比得到高度,高度*纵横比得到宽度,因此图像可以正确地上下缩放 :/

应该很容易转换成JavaScript或其他语言。

//////////////

private void ResizeImage(Image img, double maxWidth, double maxHeight)
{
    double srcWidth = img.Width;
    double srcHeight = img.Height;

    double resizeWidth = srcWidth;
    double resizeHeight = srcHeight;

    double aspect = resizeWidth / resizeHeight;

    if (resizeWidth > maxWidth)
    {
        resizeWidth = maxWidth;
        resizeHeight = resizeWidth / aspect;
    }
    if (resizeHeight > maxHeight)
    {
        aspect = resizeWidth / resizeHeight;
        resizeHeight = maxHeight;
        resizeWidth = resizeHeight * aspect;
    }

    img.Width = resizeWidth;
    img.Height = resizeHeight;
}

如果图片的高度和宽度都小于最大高度maxHeight和最大宽度maxWidth,则不会对图像进行放大。 - tech20nn

0

如果您需要完美的高度和宽度比例,这是一个很好的解决方案。裁剪后它将给出完美的裁剪比例。

getPerfectRatio(img,widthRatio,heightRatio){

  if(widthRatio < heightRatio){
    var height = img.scalingHeight - (img.scalingHeight % heightRatio);
    var finalHeight = height
    var finalWidth = widthRatio * (height/heightRatio);

    img.cropHeight = finalHeight;
    img.cropWidth = finalWidth
  }
  if(heightRatio < widthRatio){;
    var width = img.scalingWidth - (img.scalingWidth % widthRatio);
    var finalWidth = width;
    var finalHeight  = heightRatio * (width/widthRatio);
    img.cropHeight = finalHeight;
    img.cropWidth = finalWidth
  }

  return img
  
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接