javascript - 你如何计算javascript中html表格的最小宽度?
问题描述
我有一个跨越大部分页面的表格。宽度为calc(100% - 20px)
。
当我将窗口拖得很大时,表格会调整以占据整个窗口。
当我将窗口缩小得更小时,它会再次调整以占据整个窗口,但在某个点它会停止调整并溢出窗口边缘。
我想知道如何在 JS 或 jQuery 中计算表格的“最小允许宽度”,而无需实际更改窗口的大小,然后执行 a$('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>
推荐阅读
- reactjs - Redux Store 不获取图像文件
- jquery - 为什么我不能使用 jQuery 在 Wordpress 中定位存档下拉列表?
- web-scraping - Parsing and extracting data to pandas using BeautifulSoup
- elasticsearch - How to integrate spring data elastic search with DDD principles?
- ibm-cloud-infrastructure - Softlayer Virtual Guest - Invalid value provided for tags
- javascript - Importing ng-redux just returns a string
- c# - WPF Binding a collection of collections to a DataGrid
- c# - 将包含数据的大对象传递到接口中
- php - 坚持使用 PHP 和 Regex 为 MYSQL 准备 DHCP 输出
- html - VBA 粘贴到列 IF 单元格 x 中的日期等于列 y 中的日期