Javascript 如何为多个表标题创建粘性标题?
因此,我有一个包含多个行和列的多个表。由于信息量很大,我希望在滚动时将表头固定在顶部。 当一个标题出现时,前一个标题将隐藏,当前标题将保持不变 这是我到目前为止的js代码:Javascript 如何为多个表标题创建粘性标题?,javascript,jquery,Javascript,Jquery,因此,我有一个包含多个行和列的多个表。由于信息量很大,我希望在滚动时将表头固定在顶部。 当一个标题出现时,前一个标题将隐藏,当前标题将保持不变 这是我到目前为止的js代码: function makeTableHeadersSticky(tableId) { var thArr = $(tableId + " th"); var thWidthsArr = []; var calcWidth = 0; $(tableId + " th").each(function(){ calcWi
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");
如果你在我的代码中看到,我用表的位置和表的最后一行来查看表的位置。这样我可以将收割台位置设置为固定或静态
这是我的这里一切正常。您刚才忽略了为第二个表调用
makeTableHeadersSticky
函数:
makeTableHeadersSticky("#myTable2");