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

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

    Here is a solution that builds upon the accepted answer. It corrects for: column widths, matching table style, and when the table is scrolled in a container div.

    Usage

    Ensure your table has a tag because only thead content will be fixed.

    $("#header-fixed").fixHeader();
    

    JavaSript

    //Custom JQuery Plugin
    (function ($) {
        $.fn.fixHeader = function () {
            return this.each(function () {
                var $table = $(this);
                var $sp = $table.scrollParent();
                var tableOffset = $table.position().top;
                var $tableFixed = $("")
                    .prop('class', $table.prop('class'))
                    .css({ position: "fixed", "table-layout": "fixed", display: "none", "margin-top": "0px" });
                $table.before($tableFixed);
                $tableFixed.append($table.find("thead").clone());
    
                $sp.bind("scroll", function () {
                    var offset = $(this).scrollTop();
    
                    if (offset > tableOffset && $tableFixed.is(":hidden")) {
                        $tableFixed.show();
                        var p = $table.position();
                        var offset = $sp.offset();
    
                        //Set the left and width to match the source table and the top to match the scroll parent
                        $tableFixed.css({ left: p.left + "px", top: (offset ? offset.top : 0) + "px", }).width($table.width());
    
                        //Set the width of each column to match the source table
                        $.each($table.find('th, td'), function (i, th) {
                            $($tableFixed.find('th, td')[i]).width($(th).width());
                        });
    
                    }
                    else if (offset <= tableOffset && !$tableFixed.is(":hidden")) {
                        $tableFixed.hide();
                    }
                });
            });
        };
    })(jQuery);
    

    提交回复
    热议问题