【问题标题】:How do you calculate the smallest width of an html table in javascript?你如何计算javascript中html表格的最小宽度?
【发布时间】:2019-08-25 09:37:17
【问题描述】:

我有一个跨越大部分页面的表格。宽度为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);
}

【问题讨论】:

    标签: javascript jquery html-table width minimum


    【解决方案1】:

    您可以暂时在桌子上设置一个非常小的宽度,并使用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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 2011-08-20
      • 2011-05-06
      相关资源
      最近更新 更多