javascript中htmltable的最小宽度怎么计算?
How do you calculate the smallest width of an html table in javascript?
我有一个 table 横跨页面的大部分内容。宽度为calc(100% - 20px)
.
当我将 window 拖得非常大时,table 会调整以占据整个 window。
当我将 window 缩小时,它再次调整以占据整个 window 但在某个点它停止调整并溢出 window 的边缘.
我想知道如何在 JS 或 jQuery 中计算 table 的 "smallest allowed width",而无需实际更改 window 的大小然后执行$('table').width()
或类似的东西。值得注意的是,这个 "smallest allowed width" 是可变的,取决于 table 的内容。我搜索了很多,但没有找到任何好的答案。
/*table style*/
table#myTableId{
display: table;
margin: 10px;
width: -webkit-calc(100% - 20px);
width: -moz-calc(100% - 20px);
width: calc(100% - 20px);
}
您可以暂时在table上设置一个非常小的宽度,然后使用getBoundingClientRect
查看当时的实时宽度。
const table = document.getElementById('myTableId');
// get the original width in case it was set
const originalWidth = table.style.width;
// set the table's width to 1px (0 does not work)
table.style.width = '1px';
// get the current width
const smallestWidth = table.getBoundingClientRect().width;
// set the original width back
table.style.width = originalWidth;
console.log(smallestWidth);
table#myTableId {
display: table;
margin: 10px;
width: -webkit-calc(100% - 20px);
width: -moz-calc(100% - 20px);
width: calc(100% - 20px);
}
<table id="myTableId">
<tr>
<td>Table Cell Content</td>
</tr>
</table>
我有一个 table 横跨页面的大部分内容。宽度为calc(100% - 20px)
.
当我将 window 拖得非常大时,table 会调整以占据整个 window。
当我将 window 缩小时,它再次调整以占据整个 window 但在某个点它停止调整并溢出 window 的边缘.
我想知道如何在 JS 或 jQuery 中计算 table 的 "smallest allowed width",而无需实际更改 window 的大小然后执行$('table').width()
或类似的东西。值得注意的是,这个 "smallest allowed width" 是可变的,取决于 table 的内容。我搜索了很多,但没有找到任何好的答案。
/*table style*/
table#myTableId{
display: table;
margin: 10px;
width: -webkit-calc(100% - 20px);
width: -moz-calc(100% - 20px);
width: calc(100% - 20px);
}
您可以暂时在table上设置一个非常小的宽度,然后使用getBoundingClientRect
查看当时的实时宽度。
const table = document.getElementById('myTableId');
// get the original width in case it was set
const originalWidth = table.style.width;
// set the table's width to 1px (0 does not work)
table.style.width = '1px';
// get the current width
const smallestWidth = table.getBoundingClientRect().width;
// set the original width back
table.style.width = originalWidth;
console.log(smallestWidth);
table#myTableId {
display: table;
margin: 10px;
width: -webkit-calc(100% - 20px);
width: -moz-calc(100% - 20px);
width: calc(100% - 20px);
}
<table id="myTableId">
<tr>
<td>Table Cell Content</td>
</tr>
</table>