我有一个二维数据网格,其中一个表中有一个标题行,正下方的表中有多行数据(它们需要位于单独的表中)。 如果数据元素较宽,我需要标头元素的宽度自行调整为数据元素的宽度;如果标头元素较宽,我需要数据元素的宽度自行调整为标头元素的宽度。 问题是,它没有正确设置宽度。
此例程在表加载后运行:
var headtbl = document.getElementById("HeadTbl");
var bodytbl = document.getElementById("BodyTbl");
alert(headtbl.rows[0].cells[0].offsetWidth + " AND " + bodytbl.rows[0].cells[0].offsetWidth); // THIS RETURNS "**8 AND 17**"
headtbl.rows[0].cells[0].style.width = "17px"; // HARD-CODED THIS FOR DEMO PURPOSES
alert(headtbl.rows[0].cells[0].offsetWidth); // THIS RETURNS **21**!! And, obviously, the data grid is thrown off
我在网上搜索过,但没有发现这个特定问题得到解决。 有人可以帮忙吗?
编辑: 以下是演示该问题所需的绝对最低限度的代码:
<!DOCTYPE html>
<html>
<head>
<script language="JavaScript">
function formatGrid()
{
var headtbl = document.getElementById("HeadTbl");
var bodytbl = document.getElementById("BodyTbl");
alert(headtbl.rows[0].cells[0].offsetWidth + " AND " + bodytbl.rows[0].cells[0].offsetWidth); // 49 and 84
headtbl.rows[0].cells[0].width = "84px";
alert(headtbl.rows[0].cells[0].offsetWidth); // 88!
}
</script>
</head>
<body onLoad="formatGrid()">
<table id="HeadTbl" border="1">
<tr>
<td>Author</td>
</tr>
</table>
<table id="BodyTbl" border="1">
<tr>
<td>Shakespeare</td>
</tr>
</table>
</body>
</html>
您可以创建一个函数来迭代列,并计算找到最大值的两列的最小宽度。
const measureWidth = (el) => el.getBoundingClientRect().width;
const fitColumns = (frozenTable) => {
const hcells = frozenTable.querySelectorAll('.frozen-table-header thead tr th');
const bcells = frozenTable.querySelectorAll('.frozen-table-body tbody tr td');
for (let i = 0; i < hcells.length; i++) {
const minWidth = Math.max(...[hcells[i], bcells[i]].map(measureWidth));
hcells[i].setAttribute('width', minWidth);
bcells[i].setAttribute('width', minWidth);
}
};
function formatGrid() {
fitColumns(document.querySelector('.frozen-table'));
}
<body onLoad="formatGrid()">
<div class="frozen-table">
<table class="frozen-table-header" border="1">
<thead>
<tr>
<th>Author</th>
<th>Title</th>
<th>Year of Publication</th>
</tr>
</thead>
</table>
<table class="frozen-table-body" border="1">
<tbody>
<tr>
<td>Shakespeare</td>
<td>Romeo & Juliet</td>
<td>1597</td>
</tr>
</tbody>
</table>
</div>
</body>