[英]why won't my <div> resize with javascript when I tell it to?
我有一個包含表的<div>
元素,我想將其調整為最大視口高度-70 px。 原因是我希望頁眉保留在一個位置,並且表格獨立滾動。 我不能為此使用iframe,因為有復雜的javascript與表格進行交互。 因此,我必須使用<div>
並將其溢出值設置為滾動。 我的問題是,當我告訴它時,容器不會調整大小。 容器看起來像這樣:
<div class="tableContainer" id="tblCont">
<table width="100%" border="0" cellpadding="0" cellspacing="0" id="mainTbl" class="mainTable">
<tr class="row_a" id="1">
<td>id: 1</td>
</tr>
</table>
</div>
我的tableContainer類的CSS如下:
.tableContainer
{
overflow: scroll;
/*height: 400px; -- this was just to see if the concept works - and this seems to work fine */
}
最后,這是應該設置表格容器高度的javascript:
<script type="text/javascript">
var tbc = document.getElementById("tblCont");
var h = Math.round((window.innerHeight)-(70))+"px";
tbc.style.height = h;
</script>
我什至嘗試用
tbc.style.height = "50px";
但這也不起作用。
有任何想法嗎?
在DOM元素存在之前就已調用了腳本。 您需要使用onload事件處理程序調用腳本,並將腳本放入函數中:
<script type="text/javascript">
function setHeight() {
var tbc = document.getElementById("tblCont");
var h = Math.round((window.innerHeight)-(70))+"px";
tbc.style.height = h;
}
</script>
<body onload="setHeight()">
....
我認為JavaScript不會被執行。 我將其包裝在一個init函數中,並且可以正常工作。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<style type="text/css">
.tableContainer
{
overflow: scroll;
/*height: 400px; -- this was just to see if the concept works - and this seems to work fine */
}
</style>
<script type="text/javascript">
function init()
{
var tbc = document.getElementById("tblCont");
var h = Math.round((window.innerHeight)-(70))+"px";
document.getElementById('test').onclick = function()
{
tbc.style.width = "40px";
}
}
window.onload = init;
</script>
</head>
<body>
<form>
<input id="test" type="button" value="test" />
</form>
<div class="tableContainer" id="tblCont">
<table width="100%" border="0" cellpadding="0" cellspacing="0" id="mainTbl" class="mainTable">
<tr class="row_a" id="1">
<td>id: 1</td>
</tr>
</table>
</div>
</body>
</html>
嘗試兩件事:
首先,如果還沒有,請注釋掉var h行,然后手動設置高度:
<script type="text/javascript">
var tbc = document.getElementById("tblCont");
//var h = Math.round((window.innerHeight)-(70))+"px";
tbc.style.height = "50px";
</script>
其次,嘗試警告h變量而不是設置高度:
<script type="text/javascript">
var tbc = document.getElementById("tblCont");
var h = Math.round((window.innerHeight)-(70))+"px";
alert(h);
//tbc.style.height = "50px";
</script>
我的猜測是問題在於h的設置方式,然后將其殺死。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.