2013-01-03 58 views
-1

我想寫一個佈局,我有一個工具欄和一個主div。當窗口Y軸小於窗口X軸時,工具欄位於左側。當窗口X軸小於窗口Y軸時,工具欄位於頂部。 我已將絕對工具欄定位在頂部:0和左側:0,並嘗試在調整大小時更改寬度和高度屬性。但我的代碼不起作用。靈活的div佈局

的Javascript:

window.onresize = function(event) { 
winW = window.innerWidth; 
winH = window.innerHeight; 
console.debug("x axis:" + winW + "y axis:" + winH); 

if(winW < winH){ 
    var elem = document.getElementById('div1'); 

    console.debug("test" + elem.style.width); 

    var a = elem.style.height; 
    elem.style.height = elem.style.width; 
    elem.style.width = a; 

} 
else{ 
    var elem = document.getElementById('div1'); 

    elem.style.height = elem.style.height; 
    elem.style.width = elem.style.width; 
} 
} 

CSS:

#div1{ 
    background: red; 
    position:absolute; 
    height:100%; 
    width:20px; 
    top:0; 
    left:0; 
} 
#div2{ 
    width:100%; 
    height:500px; 
    background-color:green; 
    margin-left: 20px; 
} 

jsFiddle Example Here

+1

CSS @media查詢會在這個問題上做到這一點。緊要關頭_! – Kyle

+0

你應該添加一個單位! px,%.. – EricG

回答

2

給予好評爲媒體比;)

更多瀏覽器兼容的:

window.onresize = function(event) { 
    winW = window.innerWidth; 
    winH = window.innerHeight; 

    console.debug("x axis:" + winW + "y axis:" + winH); 

    document.getElementById("div1").className = (winW < winH ? "verticalMenu" : "horizontalMenu"); 
} 

// optionally invoke window.resize() once manually for setting it default. Or set a defaultClass on the div itself in HTML 

.horizontalMenu { 
    height:20px; 
    width:100%; 
} 
.verticalMenu { 
    height:100%; 
    width:20px; 
} 

參見this CodePen

6

可以使用@media screen and (min-aspect-ratio: 1/1) { ... }做到這一點。這個查詢中的任何樣式只有在窗口寬或高時纔會激活。

DEMO

我加入這個代碼,並刪除了所有的JavaScript:

@media screen and (min-aspect-ratio: 1/1) { 
    #div1 { 
     width: 100%; 
     height: 20px; 
    } 

    #div2 { 
     width: 100%; 
     margin: 0; 
    }     
} 

信息可以發現here on the MDN

對媒體查詢的支持,可以發現here,但你可以使用JavaScript我建議使用Respond.js使它們適用於所有用戶。

+0

大溶劑!非常感謝你! – Jacob

+1

這是最好的解決方案。 – Kyle

+0

只是另一個問題。我將如何使div垂直擴展以適應頁面? – Jacob