如何将html中表格头部固定


编写一个测试的表格

    <div class="table-responsive section-scroll" style="height: 600px;">
        <table class="table table-bordered" >
            <thead class="table-header">
            <tr style="background: #ffffff;">
                <td style="position: relative">             <div style="background: #ffffff;">序号</div></td>
                <td width="61"  style="position: relative;"><div style="background: #ffffff;">地域</div></td>
                <td width="119" style="position: relative;"><div style="background: #ffffff;">国家(地区)名称</div></td>
                <td width="208" style="position: relative;"><div style="background: #ffffff;">网址</div></td>
                <td width="236" style="position: relative;"><div style="background: #ffffff;">电话</div></td>
                <td width="110" style="position: relative;"><div style="background: #ffffff;">传真</div></td>
                <td width="152" style="position: relative;"><div style="background: #ffffff;">E-mail</div></td>
                <td width="201" style="position: relative;"><div style="background: #ffffff;">联系地址</div></td>
            </tr>
            </thead>
            <tbody>
            .
            .
            .
            </tbody>
        </table>
    </div>
</div>

编写JavaScript

<script>
    $(function() {
        var tableCont       = $('.section-scroll thead tr td'); //获取td
        var tableCont_child = $('.section-scroll thead tr td div'); //获取th下边的div
        var tableScroll     = $('.section-scroll'); //获取滚动条同级的class

        function scrollHandle() {
            var scrollTop = tableScroll.scrollTop();

            // 当滚动距离大于0时设置top及相应的样式
            if (scrollTop > 0) {
                tableCont.css({
                    "top": scrollTop + 'px',
                    "marginTop": "-1px",
                    "padding": 0
                });
                tableCont_child.css({
                    "borderTop": "1px solid gainsboro",
                    "borderBottom": "1px solid gainsboro",
                    "marginTop": "-1px",
                    "padding": "8px"
                })
            } else {
                // 当滚动距离小于0时设置top及相应的样式
                tableCont.css({
                    "top": scrollTop + 'px',
                    "marginTop": "0",
                });
                tableCont_child.css({
                    "border": "none",
                    "marginTop": 0,
                    "marginBottom": 0,
                })
            }
        }

        tableScroll.on('scroll', scrollHandle);
    })
</script
来源: 原创
标签: 表格 table 固定

作者介绍

Image Description

zfajax舫

小时候的梦想是当宇航员,长大的梦想是在北京买套90㎡房的小站长、自媒体人,2014年毕业,后从事过网站开发搭建工作;2016年,创建了张舫博客;20015-至今在北京工作(微信:a7983310)

评论列表

还没有人评论,抢占前排沙发

发表评论

关于作者

Image Description

zfajax舫

小时候的梦想是当宇航员,长大的梦想是在北京买套90㎡房的小站长、自媒体人,2014年毕业,后从事过网站开发搭建工作;2016年,创建了张舫博客;20015-至今在北京工作(微信:a7983310)

关注作者

Social Links

定制项目外包

Unit 25 Suite 3, 925 Prospect PI,
Beach Resort, 23001

手机号码

18600004319