13

jQueryで画像のサイズを一貫したアスペクト比に変更するにはどうすればよいですか? たとえば、最大の高さを設定し、幅を正しくサイズ変更します。ありがとう。

4

5 に答える 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'});
    });
};

基本的には、要素を取得し、親の中央に配置してから、縦横比を維持しながら、親の背景が見えないように要素を引き伸ばします。

繰り返しますが、これはあなたがやりたいことではないかもしれません。

于 2009-11-05T18:50:31.717 に答える
14

これは手動で計算できますが、

すなわち:

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

画像には必ず 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));
}
于 2009-11-05T18:20:20.243 に答える
7

JQueryUIResizeableを使用する

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

アスペクト比:true->元のアスペクト比を維持

于 2009-11-05T18:34:08.623 に答える
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;
}
于 2011-04-13T19:51:21.547 に答える