实际td的宽度是一个实数,但是我不知道offsetWidth
是否仅返回整数。是否还有其他属性返回实数单元格的长度?在chrome的开发人员工具中,按CTRL + SHIFT + C快捷键可查看长度,这是不同的。如果使用jQuery,是否可以使长度变得更容易?
function fitWidth(selector1, selector2) {
console.log('fitWidth is excuted');
let tableHeadElements = document.getElementsByClassName(selector1);
let tableBodyElements = document.getElementsByClassName(selector2);
for (let i = 0; i < tableHeadElements.length; i++) {
let tableDataOfFirstHeadTableRow = tableHeadElements[i].firstElementChild.children; // head의 첫번째 tr
let tableDataOfFirstBodyTableRow = tableBodyElements[i].firstElementChild.children; // body의 첫번째 tr
console.log("body tr count: " + tableDataOfFirstBodyTableRow.length);
for (let j = 0; j < tableDataOfFirstHeadTableRow.length; j++) {
let headCell = tableDataOfFirstHeadTableRow[j];
let bodyCell = tableDataOfFirstBodyTableRow[j];
console.log("head-cell width: " + headCell.clientWidth, "body-cell width: " + bodyCell.clientWidth);
/*
headCell.style.width = (bodyCell.offsetWidth) + "px";
headCell.style.width = (bodyCell.scrollWidth) + "px";
*/
if (headCell.clientWidth != bodyCell.clientWidth) {
headCell.clientWidth > bodyCell.clientWidth ? bodyCell.style.width = headCell.clientWidth + "px" : headCell.style.width = bodyCell.clientWidth + "px";
}
}
}
};
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<table border="1">
<thead id="a" class="queue-head">
<tr>
<td>AppName</td>
<td>QueueName</td>
<td>Server</td>
<td>Service</td>
<td>ReceptionCount</td>
<td>ProcessingCount</td>
<td>QueueCount</td>
<td>Limit</td>
<td></td>
</tr>
</thead>
</table>
<table border="1">
<tbody id="b" class="queue-body">
<tr>
<td>ABC</td>
<td>ABCDEFGHI</td>
<td>abcd01</td>
<td>9999</td>
<td>400</td>
<td>999</td>
<td>20000</td>
<td>2000</td>
<td></td>
</tr>
<tr>
<td>ABC</td>
<td>ABCDEFGHI</td>
<td>abcd01</td>
<td>9999</td>
<td>400</td>
<td>999</td>
<td>20000</td>
<td>2000</td>
<td></td>
</tr>
</tbody>
</table>
<hr />
<table border="1">
<thead class="queue-head">
<tr>
<td>AppName</td>
<td>QueueName</td>
<td>Server</td>
<td>Service</td>
<td>ReceptionCount</td>
<td>ProcessingCount</td>
<td>QueueCount</td>
<td>Limit</td>
<td></td>
</tr>
</thead>
</table>
<table border="1">
<tbody class="queue-body">
<tr>
<td>A22</td>
<td>ABCDEFGHI</td>
<td>abcd01</td>
<td>9999</td>
<td>400</td>
<td>999</td>
<td>20000</td>
<td>2000</td>
<td></td>
</tr>
<tr>
<td>A22</td>
<td>ABCDEFGHI</td>
<td>abcd01</td>
<td>9999</td>
<td>400</td>
<td>999</td>
<td>20000</td>
<td>2000</td>
<td></td>
</tr>
</tbody>
</table>
<hr />
<button onclick='fitWidth("queue-head", "queue-body");'>fit width</button>
</body>
</html>
最佳答案
您应该使用getBoundingClientRect()返回一个不四舍五入的数字。
offsetWidth和clientWidth都返回一个舍入的整数。这些页面指出:
注意:此属性会将值四舍五入为整数。如果需要分数,请使用element.getBoundingClientRect()。