2014-03-03 37 views
0

我想設置表格中單元格的高度,但我希望是動態的。我從JavaScript的窗口的高度,然後我想嵌入它的div風格。從javascript設置樣式值var

<script language="javascript"> 
var width = isNaN(window.innerWidth) ? window.clientWidth : window.innerWidth; 
var height = isNaN(window.innerHeight) ? window.clientHeight : window.innerHeight; 

if (height>900) 
{ 
    set_height = "500px"; 
} else if (height>700 && height<900) { 
    set_height = "400px"; 
} else if (height>500 && height<700) { 
    set_height = "300px"; 
} else if (height>300 && height<500) { 
    set_height = "300px"; 
} 
</script> 
<table border ="1"> 
<tr><td> 
<div style="height: set_height"> 
</div> 
</td></tr> 
</table> 

它可能嗎?

+2

添加ID到你的'div',包你代碼在窗口加載函數,並使用'document.getElementById('yourdiv')。style.height = set_height'。 – putvande

回答

0

如前所述,一個ID添加到您的div

<table border="1"> 
    <tr> 
     <td> 
      <div id="mydiv"></div> 
     </td> 
    </tr> 
</table> 

包裝你的JS在window.onload功能,通過識別添加的高度你的div:

window.onload = function() { 
    var width = isNaN(window.innerWidth) ? window.clientWidth : window.innerWidth; 
    var height = isNaN(window.innerHeight) ? window.clientHeight : window.innerHeight; 

    if (height > 900) { 
     set_height = "500px"; 
    } else if (height > 700 && height < 900) { 
     set_height = "400px"; 
    } else if (height > 500 && height < 700) { 
     set_height = "300px"; 
    } else if (height > 300 && height < 500) { 
     set_height = "300px"; 
    } 

    // Identify your div by the ID you just put on it and add the height. 
    document.getElementById('mydiv').style.height = set_height; 
} 

如果你想要這個函數被調用當你調整窗口大小,你只是window.onresize替換window.onload

window.onresize = function() { 
    // code as above 
} 

並觸發它,所以它適用於窗口負載:

window.onresize(); 

Fiddle

0

如果通過「動態」,你的意思是你希望它改變,那麼你需要做的就是每當特定事件被觸發時改變樣式值,比如當窗口調整大小時。

事情是這樣的:

window.onresize = function() { 
    var width = isNaN(window.innerWidth) ? window.clientWidth : window.innerWidth; 
    var height = isNaN(window.innerHeight) ? window.clientHeight : window.innerHeight; 

    if (height > 900) { 
     set_height = "500px"; 
    } else if (height > 700 && height < 900) { 
     set_height = "400px"; 
    } else if (height > 500 && height < 700) { 
     set_height = "300px"; 
    } else if (height > 300 && height < 500) { 
     set_height = "300px"; 
    } 

    document.getElementById('myDiv').style.height = set_height; 
}; 
window.onresize(); 

假設你的DIV有id價值myDiv,例如:

<div id="myDiv"> 
</div> 

Here is a working example

注:我可能誤解了這個問題,如果你只是希望它在頁面加載時加載(僅限一次),那麼你可以使用window.onload事件代替

爲這個目標
0

最好的辦法是:

<script> 
var set_height = "10px" 
document.getElementById('test').style.height = set_height; 
</script> 

<div id='test'></div>