【问题标题】:Synchronizing table column widths between tables在表格之间同步表格列宽
【发布时间】:2018-10-21 17:25:46
【问题描述】:

我正在尝试提出一种解决方案来同步多个表的列宽,其中列宽不固定,但宽度的确定方式与未指定宽度的单个表相同。也许能够声明一些列希望缩小到最小宽度,而另一些列希望扩展到最大宽度。

我根本没有想出一个好的解决方案。我最初尝试在 onResize 期间使用 jQuery 同步宽度......但无论如何我都无法在不影响尺寸计算的情况下设置宽度。

JQuery(通常是 DOM)似乎无法像大多数其他 UI 框架那样提供返回所需最小容器宽度的方法(啊,HTML,我多么爱你,不是)。如果我有这个能力,我会自己布置柱子。不会那么难。

有什么想法吗?

例如,我希望这些表格的列宽保持同步,而不管各个单元格中的内容如何。

<table>
  <tr><td>Col1</td><td>Col2</td><td>Col3</td><td>Col4</td></tr>
  <tr><td>Col1</td><td>Col2</td><td>Col3</td><td>Col4</td></tr>
</table>
<table>
  <tr><td>Col1</td><td>Col2</td><td>Col3</td><td>Col4</td></tr>
  <tr><td>Col1</td><td>Col2</td><td>Col3</td><td>Col4</td></tr>
</table>

【问题讨论】:

  • 你能发布一个例子来突出问题到底是什么吗?在我的jsfiddle 中,JQuery 的 width + HTML5 data-* 属性工作得很好..
  • 芥末,我看到你的历史中有很多unresolved questions。请花时间接受答案或跟进现有答案中的任何不足之处,以便将其总结。谢谢。
  • Jerome:如果我的回答回答了您的问题,请考虑将其标记为正确。谢谢!

标签: jquery html-table


【解决方案1】:

我编写了一个函数来将所有表格列宽设置为与任何表格中列的最宽版本相同。

function AlignMultipleTables(class_name)
{
    // Align tables with the specified class so that all columns line up across tables.

    // Find the max width of each column across all tables. Only look at 'th' or 'td' cells in the first row of each table.
    var col_widths = [];
    $("." + class_name).each(function(index, element) {
        $(element).find("tr:first th, tr:first td").each(function(index2, element2) {
            col_widths[index2] = Math.max(col_widths[index2] || 0, $(element2).width());
        });
    });

    // Set each column in each table to the max width of that column across all tables.
    $("." + class_name).each(function(index, element) {
        $(element).find("tr:first th, tr:first td").each(function(index2, element2) {
            $(element2).width(col_widths[index2]);
        });
    });
}

给所有表格一个类似“align-to-widest”的类,然后像这样调用函数:

AlignMultipleTables("align-to-widest");

见我的jsfiddle here.

【讨论】:

    猜你喜欢
    • 2011-04-04
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 2010-12-31
    • 2012-08-24
    • 2019-12-20
    • 2019-02-28
    • 2017-05-20
    相关资源
    最近更新 更多