gpt4 book ai didi

javascript - 你如何计算javascript中html表格的最小宽度?

转载 作者:行者123 更新时间:2023-11-30 19:39:59 25 4
gpt4 key购买 nike

我有一个横跨页面大部分的表格。宽度为 calc(100% - 20px)

当我将窗口拖得非常大时,表格会调整以占据整个窗口。

当我缩小窗口时,它会再次调整以占据整个窗口,但在某个点它会停止调整并溢出窗口的边缘。

我想知道如何在 JS 或 jQuery 中计算表格的“最小允许宽度”,而无需实际更改窗口大小然后执行 $('table').width() 或类似的东西。值得注意的是,这个“最小允许宽度”是可变的,具体取决于表格的内容。我进行了相当多的搜索,但没有找到任何好的答案。

/*table style*/ 
table#myTableId{
display: table;
margin: 10px;
width: -webkit-calc(100% - 20px);
width: -moz-calc(100% - 20px);
width: calc(100% - 20px);
}

最佳答案

您可以临时在表格上设置一个非常小的宽度,然后使用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>

关于javascript - 你如何计算javascript中html表格的最小宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55502241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com