bootstrap表头固定,无错位版

时间:2020-04-01
本文章向大家介绍bootstrap表头固定,无错位版,主要包括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>
            <thead id="table-head">
                ...
            </thead>
        </table>
        <div class="table-scroll">
            <table class="table table-striped" id="data">
                <tbody>
                    ...
                </tbody>
            </table>
        </div>
    </div>
    <!-- style="opacity: 0; -->
    <script>
        $(document).ready(function () {
            changed_original_width(200)
        })

        function changed_original_width(maxHeight) {
            // maxHeight: 表格内容的高度;
            $('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>

原文地址:https://www.cnblogs.com/xshan/p/12614330.html