分类
代码

滚动网页时固定表头

当网页的表格高度比较大时,比如超过一屏,我们希望表头能够一直显示,就像 Excel 的“首行冻结”一样。
搜索一下,看到一种思路是表头写两个,第一个只有表头,默认不显示,定位为 fixed 在顶部,第二个有表头和数据单元格。
然后滚动网页时,使用 js 计算表头是否应该显示,实时的设置可见性。

示例如下:

<table class="table fix-head-control" id="tableCtl">
    <thead>
    <tr>
        <th scope="col">#</th>
        <th scope="col">First</th>
        <th scope="col">Last</th>
        <th scope="col">Handle</th>
    </tr>
    </thead>
</table>
<table class="table table-striped table-hover table-fixed-head" data-target="#tableCtl">
    <thead>
    <tr>
        <th scope="col">#</th>
        <th scope="col">First</th>
        <th scope="col">Last</th>
        <th scope="col">Handle</th>
    </tr>
    </thead>
<tbody>...</tbody>
</table>
<style>
    .fix-head-control {
        background-color: white;
        z-index: 100;
        position: fixed;
        width: 100%;
    }
</style>
$(document).ready(function () {
    function headFixed($table, howMuch) {
        if (howMuch === undefined) {
            howMuch = 56;
        }
        $(window).scroll(function () {
            var $target = $($table.data('target'));
            var topDis = $table.offset().top - $(window).scrollTop();
            var bottomDis = $table.height() + $table.offset().top - $(window).scrollTop() - $target.height();
            if (topDis < howMuch && bottomDis > howMuch) {
                $target.removeClass('invisible');
                $target.css('top', howMuch + 'px');
            } else {
                $target.css('top', 0);
                $target.addClass('invisible');
            }
        });
    }

    $('.table-fixed-head').each(function () {
        headFixed($(this));
    });
});

用法:
HTML 定义两个元素,一个是滚动时要固定在顶部的元素,暂且称为固定元素,需要有个 id;另一个是在视口滚动的元素的本身,称为滚动元素,用 data-target 属性指向固定的元素。
固定元素要默认不可见,注意不是 display:none, 而是 visibility: hidden,这样它的高度还在;同时定位方式设置为 fixed,top 在滚动时设置。

上面的 headFixed 方法需要传入两个参数,一个滚动元素,一个高度值。该方法会实时计算滚动元素的顶部是否到了给定的高度值、滚动元素的底部是否过掉了给定的高度值。然后将固定元素的 top 设置为给定的高度值。
GitHub 源代码:https://github.com/YouthLin/examples/blob/master/gnqc/tableFixedHead.html
Demo 地址:https://youthlin.com/demo/tableHeadFixed.html


发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

[/鼓掌] [/难过] [/调皮] [/白眼] [/疑问] [/流泪] [/流汗] [/撇嘴] [/抠鼻] [/惊讶] [/微笑] [/得意] [/大兵] [/坏笑] [/呲牙] [/吓到] [/可爱] [/发怒] [/发呆] [/偷笑] [/亲亲]