jQuery调整宽高比

use*_*est 13 javascript jquery image scale

我如何将jQuery中的图像调整为一致的宽高比.例如,设置最大高度并正确调整宽度.谢谢.

Eri*_*ric 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'});
    });
};
Run Code Online (Sandbox Code Playgroud)

基本上,它抓取一个元素,将其置于父级中心,然后将其拉伸以使父级的背景都不可见,同时保持宽高比.

然后,这可能不是你想要做的.

  • 谢谢,这是一个巨大的帮助! (2认同)

Pau*_*aul 13

你可以手动计算,

即:

function GetWidth(newHeight,orginalWidth,originalHeight)
{
if(currentHeight == 0)return newHeight;
var aspectRatio = currentWidth / currentHeight;
return newHeight * aspectRatio;
}
Run Code Online (Sandbox Code Playgroud)

确保使用图像的ORIGINAL值,否则它会随着时间的推移而降级.

编辑:示例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));
}
Run Code Online (Sandbox Code Playgroud)


Jas*_*wig 9

使用JQueryUI Resizeable

$("#some_image").resizable({ aspectRatio:true, maxHeight:300 });
Run Code Online (Sandbox Code Playgroud)

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

  • 同意,但这是你不需要编写/维护的代码. (4认同)