【问题标题】:Fast way to align row heights in 2 different tables在 2 个不同的表格中对齐行高的快速方法
【发布时间】:2013-09-12 13:05:45
【问题描述】:

目前使用此 javascript 函数通过匹配 2 个不同表中的高度来对齐所有行。每个表有 1000 多行。而这个函数的执行时间超过 4 秒。有没有更快的方法来匹配两个不同表的行高?谢谢

function alignTableRowHeights() {
    $('#table1 tr').each(function(i) {
        var rowDisplay=$(this).css("display")
        if(rowDisplay!="none"){
            // Row is visible
            var tableTwoRow = $('#table2 tr').get(i);
            var height = $(tableTwoRow).height();        
            $(this).height(height);
        }
    });
}

表格中的行高度不同。因此需要有逻辑来单独获取每行的高度。并且某些行可能被隐藏(用于展开和折叠),因此需要检查行是否显示。目的是并排显示两个表格,因此可见行需要保持同步和对齐。

【问题讨论】:

  • 您可能希望研究一种仅呈现屏幕上可见行的 JavaScript 解决方案,这样您就不会浪费时间更改隐藏行的位置。第一个想到的库是github.com/mleibman/SlickGrid
  • 为什么需要脚本?你不能只为表格设置相同的类并将 tr{height:20px;} 调整为两者吗?

标签: javascript html css performance


【解决方案1】:

只有 Javascript 会是最快的,然而,最慢的可能不是 jQuery 本身,而是你如何使用它:

  1. 对于每一行,您查询所有其他行只是为了使用一个。解决方案:在该表的循环之前获取您的查询结果
  2. 对于您要求从计算样式中提取显示属性的每一行。解决方案:使用 jQuery 的 :visible 选择器,这样您就不必执行单独的检查。
  3. 有时在表格可见时对 DOM 的操作可能会非常缓慢,具体取决于您的布局、样式等。解决方案:从 dom 中删除您正在更新的表格,更新高度,然后将其放回原处。

我可以这样做:

function alignTableRowHeights() {

    // copy the heights into an array
    var heights = [];
    $('#table2').find('tr:visible').each(function(i) {
        heights[i] = $(this).height();
    });

    // get visible table one rows before we remove it from the dom
    var tableOneRows = $('#table1').find('tr:visible');

    // remove table one from the dom
    var tempDiv = $('<div />');
    var table1 = $('#table1');
    table1.replaceWith(tempDiv);

    $.each(tableOneRows, function(i) {
        $(this).height(heights[i]);
    });

    // put table one back in the dom
    tempDiv.replaceWith(table1);

}

【讨论】:

  • 谢谢。您的实施确实提高了性能。对于每个 1000 行的表,Chrome 的性能可以接受,但在 IE 8 中仍然很慢。
  • 不幸的是,这通常是使用 IE8 的副作用。当我的许多项目包含复杂的 UI 时,我很难在 IE8 中获得合理的性能。如果您想尝试一些,您也可以尝试将表格保留在 dom 中。显然,如果您可以将两个表合并为一个,您将获得最佳性能,因为您不需要 JS 来使行高匹配,但我猜这不是一个选择。
【解决方案2】:

只需隐藏表格直到高度固定:

function alignTableRowHeights () {
    $('#table1').css('display', 'none');
    $('#table1 tr').each(function (i) {
        var rowDisplay = $(this).css("display")
        if (rowDisplay != "none") {
            // Row is visible
            var tableTwoRow = $('#table2 tr').get(i);
            var height = $(tableTwoRow).height();
            $(this).height(height);
        }
    });
    $('#table1').css('display', '');
}

A live demo at jsFiddle.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    相关资源
    最近更新 更多