[英]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.