我想设置表格中单元格的高度,但我想动态设置。我从javascript中获取窗口的高度,然后我想以div样式嵌入它。
<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>
可能吗?
如前所述,将 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.onload
替换为window.onresize
:
window.onresize = function() {
// code as above
}
并触发它,使其在窗口加载时工作:
window.onresize();
小提琴
实现此目标的最佳方法是:
<script>
var set_height = "10px"
document.getElementById('test').style.height = set_height;
</script>
<div id='test'></div>
如果您所说的"动态"是指您希望它更改,那么您需要做的是在每次触发特定事件时更改样式值,例如当窗口调整大小时。
像这样:
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>
这是一个工作示例
注意:我可能误解了这个问题,如果您只想在页面加载时加载它(仅一次),那么您可以使用 window.onload
事件代替