js簡單固定table表頭及css問題分析。


<head>
    <meta name="viewport" content="width=device-width" />
    <title>Test02</title>
    <script src="~/Content/js/jquery-1.7.2.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#tabhead").css("width", $("#MyTable").css("width"));
            $("#tabdiv").scroll(function () { // 滾動條移動事件
                var yheight = $("#tabdiv").scrollTop(); // 滾動條距頂端的距離
                $("#tabhead").css("top", yheight + "px");
            });
        });
    </script>
</head>
<body>
    <div id="tabdiv" style="width: 500px; height: 150px; overflow: auto; position: relative; ">
        <table id="MyTable" style=" text-align: center; table-layout: fixed; width: 100%;margin-top:50px;">
            <col width="105" />
            <col width="105" />
            <col width="70" />
            <col width="70" />
            <col width="70" />
            <col width="80" />
            <col width="80" />
            <col width="80" />
            <thead id="tabhead" style="position: absolute;width:100%; top:0px;background-color:lightblue;">
                <tr style="">
                    <th colspan="2" style="width: 210px;"><input type="checkbox" class="chbAll" checked="checked">課程</th>
                    <th style="width:70px;">總分</th>
                    <th style="width: 70px;">總分排名</th>
                    <th style="width: 70px;">平均分</th>
                    <th style="width: 80px;">平均分排名</th>
                    <th style="width: 80px;"> <input type="checkbox" class="chbKC" checked="checked">數學<br>百分制</th>
                    <th style="width: 80px;"> <input type="checkbox" class="chbKC" checked="checked">語文<br>等級制</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>---</td>
                    <td>---</td>
                    <td>---</td>
                    <td>---</td>
                    <td>---</td>
                    <td>---</td>
                    <td>---</td>
                    <td>---</td>
                </tr>
            </tbody>
        </table>
</div> </body>

只用幾行js,加幾個css樣式。不用貼層或改動表結構。(測試時請多加幾行tr)

結果如圖:上下滾動,thead不動;左右滾動,thead跟隨移動

 

分析:

將thead 設為absolute定位,使之脫離文檔流,再獲取垂直滾動條距離頂部的滾動距離,作為thead 的top位置,並實時同步。

問題一:thead 脫離文檔流后,超出tabdiv不會隱藏,且tbody上部會被遮擋。

解決:1,將tabdiv設為relative或absolute定位;2,為table加上上邊距來抵消thead的高度,margin-top:50px;。

 

問題二:table超出div寬度后,tbody單元格會自動被壓縮。

解決:table 樣式加上table-layout: fixed; width: 100%;

並通過<col />元素來設置每列寬度。

 

問題三:thead超出div寬度后,thead單元格會自動被壓縮,而tbody正常顯示。

解決:js中直接將thead的寬度設為table的寬度,$("#tabhead").css("width", $("#MyTable").css("width"));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM