我想在表格中设置单元格的高度,但我希望动态。我从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>
是否可能?
答案 0 :(得分: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>
注意:我可能误解了这个问题,如果您只想在页面加载时加载(仅限一次),那么您可以使用window.onload
事件
答案 1 :(得分:0)
实现这一目标的最佳方式是:
<script>
var set_height = "10px"
document.getElementById('test').style.height = set_height;
</script>
<div id='test'></div>
答案 2 :(得分:0)
如上所述,为div
添加ID:
<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();