如何为几个表头创建粘性标头?

时间:2014-09-05 13:20:33

标签: javascript jquery

所以我有几个包含多个行和列的表。由于信息很大,我想在滚动时将表头固定在顶部。 当一个标题出现时,前一个标题将隐藏,当前标题将保持不变。

这是我到目前为止的js代码:

function makeTableHeadersSticky(tableId) {

var thArr = $(tableId + " th");
var thWidthsArr = [];
var calcWidth = 0;
$(tableId + " th").each(function(){
    calcWidth = $(this).css("width");
    thWidthsArr.push(calcWidth);
});

var pos = $(tableId).offset();

var thTop = pos.top + "px";

var count = 0;
$(tableId + " tr:first-child > th").each(function(){
    $(this).css("width", thWidthsArr[count]);
    count++;
});
count = 0;

$(tableId + " tr:last-child > td").each(function(){
    $(this).css("width", thWidthsArr[count]);
    count++;
});

$(window).scroll(function() {

    //var firstRow = $(tableId + " tr:first-child").offset();
    var lastRow = $(tableId + " tr:last-child").offset();
    var w = $(window);
    //console.log("(first,last): ("+(firstRow.top-w.scrollTop())+","+(lastRow.top-w.scrollTop())+")");

    if(($(window).scrollTop() > pos.top) && (lastRow.top-w.scrollTop() >= 0)) {
        $(tableId + " tr:first-child").css("position", "fixed");
        $(tableId + " tr:first-child").css("top", "0px");
        $(tableId + " tr:first-child").css("left", "9px");
    } else {                        
        $(tableId + " tr:first-child").css("position", "static");
        $(tableId + " tr:first-child").css("top", thTop);

    }
});

}

makeTableHeadersSticky("#myTable");

如果您看到我的代码,我会使用表格的位置和表格的最后一行来查看表格的位置。这样我就可以将标题位置设置为固定或静态。

这是我的jsfiddle

1 个答案:

答案 0 :(得分:2)

这里的一切都很好用。您刚刚省略了为第二个表调用makeTableHeadersSticky函数:

makeTableHeadersSticky("#myTable2");

demo

相关问题