gpt4 book ai didi

javascript - 如何为多个表头制作粘性标题?

转载 作者:行者123 更新时间:2023-12-02 17:01:16 25 4
gpt4 key购买 nike

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

这是我到目前为止的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

最佳答案

这里一切正常。您只是省略了为第二个表调用 makeTableHeadersSticky 函数:

makeTableHeadersSticky("#myTable2");

demo

关于javascript - 如何为多个表头制作粘性标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25686883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com