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

后端 未结 25 2167
悲&欢浪女
悲&欢浪女 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:34

    I too experienced the same issues with the border formatting not being shown using entrophy's code but a few little fixes and now the table is expandable and displays all css styling rules you may add.

    to css add:

    #maintable{width: 100%}    
    

    then here is the new javascript:

        function moveScroll(){
        var scroll = $(window).scrollTop();
        var anchor_top = $("#maintable").offset().top;
        var anchor_bottom = $("#bottom_anchor").offset().top;
        if (scroll > anchor_top && scroll < anchor_bottom) {
            clone_table = $("#clone");
            if(clone_table.length === 0) {          
                clone_table = $("#maintable").clone();
                clone_table.attr({id: "clone"})
                .css({
                    position: "fixed",
                    "pointer-events": "none",
                     top:0
                })
                .width($("#maintable").width());
    
                $("#table-container").append(clone_table);
                // dont hide the whole table or you lose border style & 
                // actively match the inline width to the #maintable width if the 
                // container holding the table (window, iframe, div) changes width          
                $("#clone").width($("#maintable").width());
                // only the clone thead remains visible
                $("#clone thead").css({
                    visibility:"visible"
                });
                // clone tbody is hidden
                $("#clone tbody").css({
                    visibility:"hidden"
                });
                // add support for a tfoot element
                // and hide its cloned version too
                var footEl = $("#clone tfoot");
                if(footEl.length){
                    footEl.css({
                        visibility:"hidden"
                    });
                }
            }
        } 
        else {
            $("#clone").remove();
        }
    }
    $(window).scroll(moveScroll);
    

提交回复
热议问题