调整高度&调整大小时弹出窗口的宽度以保持宽高比

时间:2012-05-09 05:52:51

标签: javascript resize

我正在使用window.open函数

打开一个弹出窗口
window.open('some_page.htm','','width=950,height=500');

现在我想要的是当用户试图调整窗口大小时,应该保持宽高比,即如果宽度减小,那么相应的高度也应该减小,反之亦然。我只是想计算新的尺寸。到目前为止,我已经尝试了这个

function ResizeWindow()
{
    var iOrignalWidth = 950;
    var iOrignalHeight = 500;
    var iOuterHeight = window.outerHeight;
    var iOuterWidth = window.outerWidth;

    var iNewOuterWidth = Math.round((iOrignalWidth / iOrignalHeight) * iOuterHeight);
    var iNewOuterHeight = Math.round((iOrignalHeight / iOrignalWidth) * iNewOuterWidth);

    alert("New Width: "+ iNewOuterWidth + "\t" + "New Height" + iNewOuterHeight);
}

我知道那里出了点问题,因为我没有得到理想的结果。对此有何解决方案?

2 个答案:

答案 0 :(得分:1)

你想要将宽度调整到高度,反之亦然,而不是两者。 在此代码中,我假设您希望将宽度调整为高度:

function ResizeWindow()
{
    var iOrignalWidth = 1000;
    var iOrignalHeight = 500;
    var iOrginalRatio = iOrignalWidth/iOrignalHeight; // 2

    var iOuterWidth = window.outerWidth; // example: 1083
    var iOuterHeight = window.outerHeight; //example: 600

    var iNewOuterHeight = iOuterHeight; // 600
    var iNewOuterWidth = Math.round(iNewOuterHeight*iOrginalRatio); //600 * 2 = 1200

    alert("New Width: "+ iNewOuterWidth + "\t" + "New Height" + iNewOuterHeight);
}​

我为示例更改为原始宽度为1000,但您可以在实际代码中将其更改回来。

答案 1 :(得分:0)

你应该根据一个调整大小来保持宽高比。例如:

function ResizeWindow()
{
    var iOrignalWidth = 950;
    var iOrignalHeight = 500;
    var iOuterHeight = window.outerHeight; 
    var iOuterWidth = window.outerWidth;

    var w = (window.outerWidth  - iOrignalWidth) / iOrignalWidth; // for exam: (1280-950) / 950= 0.34
    var h = (window.outerHeight - iOrignalHeight) / iOrignalHeight; // for exam : (800 - 500) / 500= 0.60

    var newWidth;
    var newHeight;
    if (w<h)
    {
        // If percentage of width is less than percentage of height, Resize should be according to percentage of width.
        newWidth = iOrignalWidth * w * 100;
        newHeight = iOrignalHeight * w *100;
    }
    else
    {
        // If percentage of height is less than  percentage of width, Resize should be according to percentage of height.
        newWidth = iOrignalWidth * h * 100;
        newHeight = iOrignalHeight * h *100;
    }

    alert("New Width: "+ newWidth + "\t" + "New Height" + newHeight );

}

因此始终保持纵横比。