表格中的持久表头

Avatar of Chris Coyier
Chris Coyier

当您向下滚动包含长表格的页面时,表格的表头通常会滚动消失并变得无用。此代码克隆表格表头,并在您滚动到其下方时将其应用于页面顶部,并在您滚动到表格末尾时消失。

如今,您可能最好 使用position: sticky; 而不是使用 JavaScript,但您需要自行处理浏览器兼容性问题。

function UpdateTableHeaders() {
   $("div.divTableWithFloatingHeader").each(function() {
       offset = $(this).offset();
       scrollTop = $(window).scrollTop();
       if ((scrollTop > offset.top) && (scrollTop < offset.top + $(this).height())) {
           $(".tableFloatingHeader", this).css("visibility", "visible");
           $(".tableFloatingHeader", this).css("top", Math.min(scrollTop - offset.top, $(this).height() - $(".tableFloatingHeader", this).height()) + "px");
       }
       else {
           $(".tableFloatingHeader", this).css("visibility", "hidden");
           $(".tableFloatingHeader", this).css("top", "0px");
       }
   })
}

$(document).ready(function() {
   $("table.tableWithFloatingHeader").each(function() {
       $(this).wrap("<div class="divTableWithFloatingHeader" style="position:relative"></div>");
       $("tr:first", this).before($("tr:first", this).clone());
       clonedHeaderRow = $("tr:first", this)
       clonedHeaderRow.addClass("tableFloatingHeader");
       clonedHeaderRow.css("position", "absolute");
       clonedHeaderRow.css("top", "0px");
       clonedHeaderRow.css("left", "0px");
       clonedHeaderRow.css("visibility", "hidden");
   });
   UpdateTableHeaders();
   $(window).scroll(UpdateTableHeaders);
});

查看 Chris Coyier 的 CodePen 上的示例
旧的 jQuery 技术:持久表头
(@chriscoyier)
CodePen 上。