快速对齐2个不同表格中的行高

时间:2013-09-09 04:32:35

标签: javascript html css performance

目前使用此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);
        }
    });
}

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

2 个答案:

答案 0 :(得分:2)

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

  1. 对于您要查询所有其他行的每一行,只需使用一行。解决方案:在该表的循环之前获取查询结果
  2. 对于要求从计算样式中提取display属性的每一行。解决方案:使用jQuery的:visible选择器,这样您就不必执行单独的检查。
  3. 根据您的布局,样式等,有时在表可见时操作DOM可能会非常慢。解决方法:从dom中删除要更新的表,更新高度,然后将其放回原位。
  4. 以下是我如何做到这一点:

    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);
    
    }
    

答案 1 :(得分:0)

只需隐藏桌子,直到高度固定为止:

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