[英]Javascript - Resize two divs vertically on window resize
There are two divs vertically having unequal height. 垂直有两个div高度不相等。 The minimum height of each div can be
40px
. 每个div的最小高度可以为
40px
。
When i resize the browser window, I want the divs to resize maintaining the aspect ratio. 当我调整浏览器窗口的大小时,我希望div调整大小以保持纵横比。
I have created a demo in JSBIN . 我已经在JSBIN中创建了一个演示 。 It works but it gets into
Maximum call stack
. 它可以工作,但会进入
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;
})
Is their any better way of doing this or optimising the function ? 他们是这样做或优化功能的更好方法吗?
No need for Javascript; 不需要Javascript; modern browsers have got you covered.
现代化的浏览器已经覆盖了您。 Just add the
flex
property to the div
s' CSS. 只需将
flex
属性添加到div
的CSS中即可。 This example gives the div
sa 65/35 split. 本示例给出了
div
sa 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.