调整大小功能仅适用于一个维度

resize function only works in one dimension

本文关键字:一个 功能 适用于 调整      更新时间:2023-09-26

我有一个调整大小的功能,可以使主div以一致的比例调整大小。我最初让它根据窗口宽度调整大小,效果很好(函数中的第一个条件)。然后我添加了第二个条件,以便在窗口太短时,它会根据高度调整大小。 此函数在加载时正常工作。

当窗口变窄或变宽时,onresize 适用于宽度,但高度条件仅在窗口变短时才有效。如果将窗口拖得更高,则 onresize 事件似乎不会触发,我必须手动重新加载页面才能调整函数的大小。

<script>  
function contentResizeHeight() {
    var contentBG = document.getElementById("content");
    var windowHeight = window.innerHeight;
    var newHeight = Math.round(contentBG.offsetWidth * .6);
    if ( windowHeight > newHeight ){
        contentBG.style.height = newHeight + "px";
    }
    if ( windowHeight < newHeight ){
        var newerWidth = windowHeight * 1.666666666666666666;
        var newerHeight = Math.round(newerWidth * .6);
        contentBG.style.height = newerHeight + "px";
        contentBG.style.width = newerWidth + "px";
    }
};
</script>

#contentdiv 被背景图像覆盖。因此,我们的想法是保持图像宽高比相同。

div#content{
    background-repeat:no-repeat;
    background-position:center 0px;
    background-size: cover;
    min-width:1024px;
    max-width:1600px;
    min-height:614px;
    max-height:960px;
    margin-right:auto;
    margin-left:auto;
}

我在正文标签中调用函数

<body onload="contentResizeHeight()" onresize="contentResizeHeight()">

使用背景图像实现此目标

如果您尝试使用背景图像来实现此目的,则可以使用 CSS background-size: contain; 的帮助。来自Mozilla网站的关键字contain

此关键字指定背景图像应缩放为尽可能大,同时确保其两个维度都小于或等于背景定位区域的相应维度。

使用此逻辑,您几乎可以根据窗口大小根据需要放大每个维度,并让CSS完成其余的工作。

function contentResizeHeight() {
    var contentBG = document.getElementById("content"),
        windowHeight = window.innerHeight,
        windowWidth = window.innerWidth;
        contentBG.style.height = windowHeight + "px";
        contentBG.style.width = windowWidth + "px";
}

JSFiddle 在这里查看它的实际效果。

使用纯div/无背景图像时

对于碰巧偶然发现此答案以寻找与上述相同结果的人来说,这更多,但有一个普通的div(可能带有背景颜色或其他东西)并且没有 CSS 的帮助:JSFiddle

function contentResizeHeight() {
    var contentBG = document.getElementById("content"),
        windowHeight = window.innerHeight,
        windowWidth = window.innerWidth,
        contentHeight = contentBG.offsetHeight,
        contentWidth = contentBG.offsetWidth,
        newHeight = null,
        newWidth = null;
    if ( windowHeight > contentHeight ){
        // 40 is the buffer zone for increasing the windows width quickly
        if( contentWidth < windowWidth - 40 ){
            newWidth = contentHeight * 1.666666666666666666;
            if( newWidth >= windowWidth - 10 ){
                newHeight = Math.round(newWidth * .6);
            } else {
                newHeight = windowHeight;
            }
        } else {
            newHeight = Math.round(contentWidth * .6);
            newWidth = windowWidth - 4;
        }
    } else if ( windowHeight < contentHeight ){
        newHeight = windowHeight;
        newWidth = newHeight * 1.666666666666666666;
    }
    contentBG.style.height = newHeight + "px";
    contentBG.style.width = newWidth + "px";
}

这就是我设法让它工作 95% 的方式,所以如果有人有解决窗口宽度问题的方法,我很想听听。