table锁定表头

本文介绍4种固定表头方式,效果如图:

方式一、使用两个table,.tHead作为表头,tBody包含表体;

<style type="text/css">
*{margin:0; padding:0;}
table{width:100%; table-layout:fixed; border-collapse: collapse;}
tr{height:30px;}
th{text-align:left; background:#F0F1F2; border-bottom:1px solid #CCCDD1;} 
td{color:#666666; border-bottom:1px solid #CCCDD1;}
.tHead{position:fixed; left:0; top:0;}
.tBody{margin-top:30px;}
</style>
<table class="tHead">
    <tr>
        <th>title1</th>
        <th>title2</th>
        <th>title3</th>
        <th>title4</th>
        <th>title5</th>
    </tr>
</table>
        
<div class="tBody">
    <table>
        ......
    </table>
</div>

方式二:一个table

<table> 
      <thead> 
        <tr>
            <th>title1</th>
            <th>title2</th>
            <th>title3</th>
            <th>title4</th>
            <th>title5</th>
        </tr>
    </thead>
    <tbody>
        ......
    </tbody>
</table>
<style type="text/css">
*{margin:0; padding:0;}
table{border-collapse: collapse; width:100%; table-layout:fixed; margin:0 auto;}
tr{height:30px;}
th,td{border-bottom:1px solid #CCCDD1;}
thead{position:fixed; top:0px; display:table; width:100%; table-layout:fixed;}
thead tr th{background-color: #F0F1F2; border-top:1px solid #CCCDD1; text-align:left;}
tbody tr{display:table; width:100%; table-layout:fixed;}
tbody tr:first-child{margin-top:30px;}
</style>

方式三、一个table,只滚动tbody,滚动时copy一个表头显示在顶部

<style type="text/css">
*{margin:0; padding:0;}
table {border-collapse: collapse; width:100%; table-layout:fixed; margin:0 auto;}
table thead, table tbody tr {display:table; width:100%; table-layout:fixed;}
table thead{width:calc(100% - 1.5em);}
table tbody {display:block; height:300px; overflow-y:auto;}
tr{height:30px;}
th,td{border-bottom:1px solid #CCCDD1; text-align:center;}
</style>

方式四、一个table,使用jquery插件jquery.freezeheader.js

<style type="text/css">
*{margin:0; padding:0;}
table{border-collapse: collapse; width:100%; table-layout:fixed; margin:0 auto;}
tr{height:30px;}
th{background:#F0F1F2;}
th,td{border-bottom:1px solid #CCCDD1; text-align:center;}
</style>

调用:

在顶部浏览器中创建一个固定的头表:$("table").freezeHeader();

用固定高度创建一个固定的头表:$("table").freezeHeader({ 'height': '300px' });

滚动时,固定表头相对顶部位置:$("table").freezeHeader({ 'offset': '50px' });

posted @ 2016-07-29 16:45  Black_Elf  阅读(2095)  评论(0编辑  收藏  举报