Khi bạn cuộn xuống một trang có một bảng dài trên đó, thường thì tiêu đề của bảng sẽ cuộn đi và trở nên vô dụng. Mã này sao chép tiêu đề bảng và áp dụng nó ở đầu trang sau khi bạn cuộn qua nó và biến mất khi bạn cuộn qua bảng.
Ngày nay, có lẽ bạn nên sử dụng position: sticky;
tốt hơn là sử dụng JavaScript, nhưng bạn sẽ phải tự mình thực hiện cuộc gọi hỗ trợ trình duyệt đó.
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(" "); $("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); ));
Xem
Kỹ thuật jQuery Pen CŨ: Tiêu đề ổn định của Chris Coyier (@chriscoyier)
trên CodePen.