Table header to stay fixed at the top when user scrolls it out of view with jQuery

后端 未结 25 2141
悲&欢浪女
悲&欢浪女 2020-11-22 05:38

I am trying to design an HTML table where the header will stay at the top of the page when AND ONLY when the user scrolls it out of view. For example, the table may be 500

25条回答
  •  终归单人心
    2020-11-22 06:10

    You would do something like this by tapping into the scroll event handler on window, and using another table with a fixed position to show the header at the top of the page.

    HTML:

    CSS:

    #header-fixed {
        position: fixed;
        top: 0px; display:none;
        background-color:white;
    }
    

    JavaScript:

    var tableOffset = $("#table-1").offset().top;
    var $header = $("#table-1 > thead").clone();
    var $fixedHeader = $("#header-fixed").append($header);
    
    $(window).bind("scroll", function() {
        var offset = $(this).scrollTop();
    
        if (offset >= tableOffset && $fixedHeader.is(":hidden")) {
            $fixedHeader.show();
        }
        else if (offset < tableOffset) {
            $fixedHeader.hide();
        }
    });
    

    This will show the table head when the user scrolls down far enough to hide the original table head. It will hide again when the user has scrolled the page up far enough again.

    Working example: http://jsfiddle.net/andrewwhitaker/fj8wM/

提交回复
热议问题