固定頭部的表格

實現思路就是複製一下表格頭部然互覆蓋在原有的頭部上,監聽滾動事件
以前動態的設置覆蓋上去的thead裏面th的寬度在火狐下會與抖動現象,直接寫樣式就不會了
效果圖以下javascript

圖片描述

貼一下代碼:css

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="renderer" content="webkit" />
    <title>頭部固定的表格</title>
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.css" />
    <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" ></script>
    <script type="text/javascript" src="http://apps.bdimg.com/libs/bootstrap/3.3.4/js/bootstrap.min.js" ></script>
    <style>
        body {
            padding-top: 100px;
        }
        #goodsList {
            padding: 0;
            height: 400px;
            overflow-y: scroll;
        }
        .fixTable thead {
            background-color: #fff; 
        }
    </style>
</head>
<body>


<div id="goodsList" class="col-xs-offset-3 col-xs-6">
    <table id="textTable" class="table table-bordered scrollTable">
        <thead>
        <tr>
            <th width="35%">姓名</th>
            <th width="25%">年齡</th>
            <th width="20%">性別</th>
            <th width="10%">身高</th>
            <th width="10%">體重</th>
        </tr>
        </thead>
        <tbody id="testTbody"></tbody>
    </table>
</div>

<script type="text/javascript">
    
    $(document).ready(function () {

        var html = '',
            $ele = $('#testTbody');
        for(var i = 0; i < 20; i++) {
            html += "<tr><td>123456</td><td>12345</td><td>1234</td><td>123</td><td>12</td></tr>";
        }
        $ele.empty().append(html);

        var $fixTable = $('#goodsList .fixTable');
        $('#goodsList').scroll(function() {
            var id = '#' + this.id;
            var scrollTop = $(id).scrollTop() || $(id).get(0).scrollTop,
                style = {
                    'position': 'absolute',
                    'left': '0',
                    'right': '0',
                    'top': scrollTop + 'px'
                };
            if ($fixTable.length) {
                (scrollTop === 0) ? $fixTable.addClass('hidden') : $fixTable.removeClass('hidden');
                $fixTable.css(style);
            } else {
                var html = $(id + ' .scrollTable thead').get(0).innerHTML;
                var table = $('<table class="table table-bordered fixTable"><thead>' + html + '</thead></table>');
                table.css(style);
                $(id).append(table);
                $fixTable = $(this).find('.fixTable');
            }
        });
    })
</script>
</body>
</html>
相關文章
相關標籤/搜索