Fix thead on page scroll

前端 未结 4 1209
太阳男子
太阳男子 2020-12-14 04:22

Situation: A page with a table with several rows. I want to fix thead when thead reach the top of the page when scrolling, using jquery or any given scripting. I don\'t wan

4条回答
  •  眼角桃花
    2020-12-14 05:06

    Here's something that kind of works (quickly tested in FF 3.5, Chrome 3, and IE 8) that you might be able to tailor to your needs.

    It uses absolute positioning of the thead. When the thead becomes absolutely positioned, this basically removes it from the original flow of the table and the widths of all the tbody tds adjust accordingly. So you get ugly behavior if you don't specify column widths or if any column's header is wider than any other cell in that column.

    CSS

    #Grid thead.Fixed
    {
        position: absolute;
    }
    

    HTML

    A B C
    1 2 3

    jQuery

    $(function() {
        var table = $("#Grid");
    
        $(window).scroll(function() {
            var windowTop = $(window).scrollTop();
    
            if (windowTop > table.offset().top) {
                $("thead", table).addClass("Fixed").css("top", windowTop);
            }
            else {
                $("thead", table).removeClass("Fixed");
            }
        });
    });
    

    I noticed that it does not work in IE unless you specify a strict XHTML doctype:

    
    
        
    

提交回复
热议问题