2017-12-06 6 views
0

縦が等しくない2つのdivが垂直にあります。各divの最小の高さは40pxになります。Javascript - ウィンドウ上で垂直方向に2つのdivのサイズを変更する

ブラウザウィンドウのサイズを変更すると、アスペクト比を維持したままdivのサイズを変更します。

I have created a demo in 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; 
}) 

これを実行するか、機能を最適化する方法はありますか?

+0

あなたが事前に 'div'sの高さを知っていますか?あなたのデモ「div」の高さは同じです。 – AuxTaco

+0

はい事前にdivの高さを知っています。それは何でもかまいません(同じ高さ、等しくない高さ) –

+0

デモでは、divの高さが等しくない –

答えて

0

Javascriptは不要です。現代のブラウザがあなたをカバーしてくれました。 flexプロパティをdivのCSSに追加するだけです。この例では、divに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>

+0

残念ながら私はフレックスを使用できません。私は高さがピクセルで、localStorageに格納する必要があります。次のロードでは、最後の位置が記憶されるようにします。 –

関連する問題