JavaScript-在窗口大小的大小上垂直调整了两个Divs大小



有两个div的垂直高度。每个DIV的最小高度可以是40px

当我调整浏览器窗口大小时,我希望DIVS调整大小维护纵横比。

我在JSBIN创建了一个演示。它有效,但进入Maximum call stack

function divideEqually(h1, h2, diff) {
    let threshold = 40;
    let diffSplit = diff / 2;
    let leftOut1 = 0,
        leftOut2 = 0,
        leftOut = 0;
    if (h1 != threshold) {
        h1 = h1 + diffSplit;
    } else {
        leftOut1 = diffSplit;
    }
    if (h2 != threshold) {
        h2 = h2 + diffSplit;
    } else {
        leftOut2 = diffSplit;
    }
    diff = 0;
    if (h1 < threshold) {
        leftOut1 = threshold - h1;
        h1 = threshold;
    }
    if (h2 < threshold) {
        leftOut2 = threshold - h2;
        h2 = threshold;
    }
    diff = Math.ceil(leftOut1 + leftOut2);
    // error margin
    if (Math.abs(diff) > 0.5) {
        return divideEqually(h1, h2, diff);
    }
    return {
        h1: h1,
        h2: h2
    };
}
const qs = handle => document.querySelector(handle)
let initialHeight = window.innerHeight;
window.addEventListener('resize',()=>{
    const newHeight = window.innerHeight;
    const changeInHeight = newHeight - initialHeight;
    const h1 = qs("#top");
    const h2 = qs("#bottom")
    const h = divideEqually(h1.clientHeight,h2.clientHeight,changeInHeight);
    initialHeight = newHeight;
    h1.style.height = h.h1 + "px";
    h2.style.height = h.h2 + "px";
    // debug
    h1.innerHTML = h.h1;
    h2.innerHTML = h.h2;
})

他们做到这一点还是优化功能的更好方法?

javaScript不需要;现代浏览器已吸引您覆盖。只需将flex属性添加到div S'CSS中即可。此示例使div S分为65/35。

#container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
#top {
  flex: 65 0 0%;
  min-height: 40px;
  width: 200px;
  background: red;
}
#bottom {
  flex: 35 0 0%;
  min-height: 40px;
  width: 200px;
  background: orange;
}
<div id="container">
  <div id="top"></div>
  <div id="bottom"></div>
</div>

最新更新