這個是最簡單的方法,基於jQuery的解決方案,引入一個兩個js就可以解決,當然也有使用css,
position: sticky,這個我下一章節會講它的優缺點,當然為了凸顯jQuery的優點,
這裡寫圖片描述

我就說話使用css的缺點

1.固定表頭,和首列需要額外的html,結構複雜。

2.體驗效果,響應式佈局很難解決,幾乎沒有解決
,table固定了長寬,在其他頁面會看到很彆扭,影響美觀。

3.遇到bug,如果你是後端開發就需要找前端一點一點調樣式,後端噩夢,影響開發效率

現在開始介紹JQuery的思路:
步驟1:克隆元素
在我們開始之前,我們將要關閉表頭,並宣告一些變數

//宣告螢幕、當前table
    var $ t = $(this),
        $ w = $(window),
        $ thead = $(this).find('thead').clone(),
        $ col = $(this).find('thead,tbody').clone();

步驟2:建立新表
步驟3:插入克隆後的表格內容
步驟4:通過scrollTop算滾動高度來顯示新表
算了還是長話短說,不說原理了,具體js程式碼等下回帖出來,不懂的可以直接問我,直接看看怎麼使用吧。

第一步引入js

jquery.stickyheader.js
//可以去這裡下載自己重新建立一個
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-throttle-debounce/1.1/jquery.ba-throttle-debounce.min.js"></script>

第二步html中table結構

<table>
    <thead>
        <tr>
        <!-- 固定表頭是th裡面的內容 -->
            <th></th>

    </tr>
    </thead>
    <tbody>
        <tr>
         <!-- 如果你需要列表的第一列也固定 -->
         <!-- <th></th> 使用這種模式支援rowspan -->
            <td></td>

        </tr>
        <!-- more rows are possible -->
    </tbody>

</table>

css

.sticky-wrap {
    overflow-x: auto;
    position: relative;
    margin-bottom: 1.5em;
    width: 100%;
}
.sticky-wrap .sticky-thead,
.sticky-wrap .sticky-col,
.sticky-wrap .sticky-intersect {
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    transition: all .125s ease-in-out;
    z-index: 50;
    width: auto; /* Prevent table from stretching to full size */
}
    .sticky-wrap .sticky-thead {
        box-shadow: 0 0.25em 0.1em -0.1em rgba(0,0,0,.125);
        z-index: 100;
        width: 100%; /* Force stretch */
    }
    .sticky-wrap .sticky-intersect {
        opacity: 1;
        z-index: 150;
    }
    .sticky-wrap .sticky-intersect th {
        background-color: #666;
        color: #eee;
    }
.sticky-wrap td,
.sticky-wrap th {
    box-sizing: border-box;
}

第三步開啟瀏覽器看效果吧

這裡寫圖片描述

原文

  1. 線上演示1
  2. 線上演示2
  3. 線上演示3

jquery-throttle-debounce-plugin.js

(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);

jquery.stickyheader.js

 $('table').each(function() {
            if($(this).find('thead').length > 0 && $(this).find('th').length > 0) {
                // 克隆<thead>
                var $w	   = $(window),
                        $t	   = $(this),
                        $thead = $t.find('thead').clone(),
                        $col   = $t.find('thead, tbody').clone();

                // Add class, remove margins, reset width and wrap table
                $t
                        .addClass('sticky-enabled')
                        .css({
                            margin: 0,
                            width: '100%'
                        }).wrap('<div class="sticky-wrap" />');

                if($t.hasClass('overflow-y')) $t.removeClass('overflow-y').parent().addClass('overflow-y');

                // Create new sticky table head (basic)
                $t.after('<table class="sticky-thead table" />');

                // If <tbody> contains <th>, then we create sticky column and intersect (advanced)
                if($t.find('tbody th').length > 0) {
                    $t.after('<table class="sticky-col table" /><table class="sticky-intersect" />');
                }

                // Create shorthand for things
                var $stickyHead  = $(this).siblings('.sticky-thead'),
                        $stickyCol   = $(this).siblings('.sticky-col'),
                        $stickyInsct = $(this).siblings('.sticky-intersect'),
                        $stickyWrap  = $(this).parent('.sticky-wrap');

                $stickyHead.append($thead);

                $stickyCol
                        .append($col)
                        .find('thead th:gt(0)').remove()
                        .end()
                        .find('tbody td').remove();

                $stickyInsct.html('<thead><tr><th>'+$t.find('thead th:first-child').html()+'</th></tr></thead>');

                // 設定寬度
                var setWidths = function () {
                            $t
                                    .find('thead th').each(function (i) {
                                $stickyHead.find('th').eq(i).width($(this).width());
                            })
                                    .end()
                                    .find('tr').each(function (i) {
                                $stickyCol.find('tr').eq(i).height($(this).height());
                            });

                            // Set width of sticky table head
                            $stickyHead.width($t.width());

                            // Set width of sticky table col
                            $stickyCol.find('th').add($stickyInsct.find('th')).width($t.find('thead th').width())
                        },
                        repositionStickyHead = function () {
                            // Return value of calculated allowance
                            var allowance = calcAllowance();

                            // Check if wrapper parent is overflowing along the y-axis
                            if($t.height() > $stickyWrap.height()) {
                                // If it is overflowing (advanced layout)
                                // Position sticky header based on wrapper scrollTop()
                                if($stickyWrap.scrollTop() > 0) {
                                    // When top of wrapping parent is out of view
                                    $stickyHead.add($stickyInsct).css({
                                        opacity: 1,
                                        top: $stickyWrap.scrollTop()
                                    });
                                } else {
                                    // When top of wrapping parent is in view
                                    $stickyHead.add($stickyInsct).css({
                                        opacity: 0,
                                        top: 0
                                    });
                                }
                            } else {
                                // If it is not overflowing (basic layout)
                                // Position sticky header based on viewport scrollTop
                                if($w.scrollTop() > $t.offset().top && $w.scrollTop() < $t.offset().top + $t.outerHeight() - allowance) {
                                    // When top of viewport is in the table itself
                                    $stickyHead.add($stickyInsct).css({
                                        opacity: 1,
                                        top: $w.scrollTop() - $t.offset().top
                                    });
                                } else {
                                    // When top of viewport is above or below table
                                    $stickyHead.add($stickyInsct).css({
                                        opacity: 0,
                                        top: 0
                                    });
                                }
                            }
                        },
                        repositionStickyCol = function () {
                            if($stickyWrap.scrollLeft() > 0) {
                                // When left of wrapping parent is out of view
                                $stickyCol.add($stickyInsct).css({
                                    opacity: 1,
                                    left: $stickyWrap.scrollLeft()
                                });
                            } else {
                                // When left of wrapping parent is in view
                                $stickyCol
                                        .css({ opacity: 0 })
                                        .add($stickyInsct).css({ left: 0 });
                            }
                        },
                        calcAllowance = function () {
                            var a = 0;
                            // Calculate allowance
                            $t.find('tbody tr:lt(3)').each(function () {
                                a += $(this).height();
                            });

                            // Set fail safe limit (last three row might be too tall)
                            // Set arbitrary limit at 0.25 of viewport height, or you can use an arbitrary pixel value
                            if(a > $w.height()*0.25) {
                                a = $w.height()*0.25;
                            }

                            // Add the height of sticky header
                            a += $stickyHead.height();
                            return a;
                        };

                setWidths();

                $t.parent('.sticky-wrap').scroll($.throttle(250, function() {
                    repositionStickyHead();
                    repositionStickyCol();
                }));

                $w
                        .load(setWidths)
                        .resize($.debounce(250, function () {
                            setWidths();
                            repositionStickyHead();
                            repositionStickyCol();
                        }))
                        .scroll($.throttle(250, repositionStickyHead));
            }
        });

2018.7.13 又發現一個好外掛,如果你用過datatable可以使用fixedheader來固定頭部,使用fixedcolumns固定列
https://datatables.net/extensions/fixedheader/
如果你遇到問題,可以加群315552185
一起交流哦!

.