bootstrap表头固定,无错位版

原理:表头写一个table中,表格的内容写在另一个table中,表头的宽度同步下面的表格内容的宽度

模板:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.4.1.slim.js"
        integrity="sha256-BTlTdQO9/fascB1drekrDVkaKd9PkwBymMlHOiG+qLI=" crossorigin="anonymous"></script>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
        crossorigin="anonymous"></script>
    <title>bootstrap表头固定</title>
</head>

<body>
    <div class="container theme-showcase" role="main">
        <table id="table-head">
            <thead id="table-head">
                ...
            </thead>
        </table>
        <div class="table-scroll">
            <table class="table table-striped">
                <tbody>
                    ...
                </tbody>
            </table>
        </div>
    </div>
    <script>
        $(document).ready(function () {
            tableFixed(200)
        })

        function tableFixed(maxHeight) {
            // maxHeight: 表格内容的高度;
       $('table#table-head').css({'margin-bottom': '0'});

$('div.table-scroll').css({ 'display': 'block', 'max-height': maxHeight + 'px', 'overflow-y': 'scroll' })
var tdWidthObj = new Array();
            $('div.table-scroll').find('tr').first().children('td').each(function () {
                let td_width = $(this).outerWidth()
                tdWidthObj.push(td_width)
            });
            var i = 0
            $('thead#table-head').find('tr').first().children('th').each(function () {
                $(this).css('width', tdWidthObj[i])
                i++
            })
        }
    </script>
</body>

</html>

 

posted @ 2020-04-01 18:00  xsan  阅读(628)  评论(0编辑  收藏  举报