html表格固定表头

1、CSS部分

 .fix-head-control {
            z-index: 100;
            position: fixed;
        }

        .invisible {
            visibility: hidden;
        }

2、js部分

<script type="text/javascript">
        
        $(function() {
            appendTableFixHead();
        });

        window.onresize = initFixTableHeadSize;
        function initFixTableHeadSize() {
            $('table.grid[type="head"]').css("width", $('table.grid[type="data"]').css("width"));
            var headTds = $('table.grid[type="data"] tbody>tr:eq(0)').children();
            var fixHeadTds = $('table.grid[type="head"] tbody>tr:eq(0)').children();
            for (var i = 0; i < headTds.length; i++) {
                $(fixHeadTds[i]).width($(headTds[i]).width());
            }
        }
        function appendTableFixHead() {
            var headTr = $('table.grid[type="data"] tbody>tr:eq(0)');
            var headTable = '<table width="100%" class="grid fix-head-control invisible" type="head" style="top: 0px;"><tbody><tr>';
            headTable += headTr.html() + "</tr></tbody></table>";

            $('table.grid[type="data"]').before(headTable);

            initFixTableHeadSize();
            headFixed($('table.grid[type="data"]'), -5);
            
        }

        function headFixed($table, headMarginTop) {
            if (headMarginTop === undefined) {
                headMarginTop =0;
            }
            $(window).scroll(function () {
                var $target = $('table.grid[type="head"]');
                $target.css('left', 0 - $(window).scrollLeft() + $table.offset().left);
                var topDis = $table.offset().top - $(window).scrollTop();
                if (topDis < headMarginTop) {
                    $target.removeClass('invisible');
                    $target.css('top', headMarginTop + 'px');
                } else {
                    $target.css('top', 0);
                    $target.addClass('invisible');
                }
            });
        }
    </script>

3、html部分

<table class='grid' type='data'>
  <tbody>
     <tr></tr>
     <tr></tr>
     ...
  </tbody>
</table>

 

posted @ 2022-05-17 15:20  潇潇与偕  阅读(1784)  评论(0编辑  收藏  举报