# 固定表格欄位 類似excel凍結窗格的功能 ![](https://i.imgur.com/MYvuDPy.gif) 可以用純css進行設定 關鍵字:``position:sticky`` --- ## 範例 因為border不會隨著被固定的欄位一起移動(表格中會出現奇怪的裂縫) 表格框線均改用內陰影替代 ### 1.固定欄位(一欄一列) 有包外框,貼齊外框邊界 [範例連結](https://codepen.io/GoldfishIsGood/full/JjBWbKr) ![](https://i.imgur.com/Bq3Loyx.png) 1. 針對**th(首列)**、**tr的第一個td**(首欄)和**首欄首列交叉的欄位**,設定 ```css= position:sticky ``` 2. 逐項設定貼齊的邊界和z-index ```css= left:0;/*ex.貼齊左側邊界,距離0*/ z-index:3;/*交叉點>首欄=首列>其他格子*/ ``` --- ### 2. 固定欄位(多欄多列) 沒有包外框,直接貼齊畫面邊界 [範例連結](https://codepen.io/GoldfishIsGood/full/QWBppmz) ![](https://i.imgur.com/i1Cyems.png) 1. 給要固定的欄位設定position ```css= position:sticky ``` 和一行一列的設定方式差不多, 不過另外給個class名稱會更好操作,尤其是首欄可能是合併欄位的情況。 範例固定的是**首欄**、**第二欄**、**首列**和**第二列**,以及交叉點的合併欄位 都分別給了不同的class名稱以便設定與邊界的距離 2. 首欄和首列設定貼齊的邊界和z-index ```css= left:0;/*ex.貼齊左側邊界,距離0*/ z-index:2;/*交叉點>首欄=首列=第二欄or列>其他格子*/ ``` 3. 第二欄和第二列設定貼齊的邊界和z-index ```css= left:30px;/*以左邊界為基準,推移一個td的距離,以免覆蓋首欄或首列*/ z-index:2;/*交叉點>首欄=首列=第二欄or列>其他格子*/ ``` --- ### 3. 依欄位高度和寬度動態調整 ^*非純CSS^ 當文字可能過長導致td的寬度或高度自動延伸時,改用jq的方法去抓當前的真正高度或寬度。 適用於無法確定內容的寬和高的動態產生table。 [範例連結](https://codepen.io/GoldfishIsGood/full/bGQVZJg) >測試時有發生特定字重或特定字體大小時表格裂開的情況, >因為td的實際高度是小數,但使用css抓到的高度自動進位,導致下推的高度差1,因此出現裂縫 <!-- ```javascript= function settingColRow(intCol, intRow) { //先橫再直,intCol = 要釘住幾個直欄,intRow = 要釘住幾個橫列 for (var i = 1; i <= intCol; i++) { $('.tg tr td:nth-child(' + i + ')').css('z-index', '2').css('color', 'purple'); if (i == 1) { $('.tg tr td:nth-child(1)').css('left', '0px'); } else { var intLeft = parseFloat($('.tg tr td:nth-child(' + (i - 1) + ')').css('left').replace('px', '')) + parseFloat($('.tg tr td:nth-child(' + (i - 1) + ')').css('width').replace('px', '')) + 10 + 'px'; //10=左+右padding $('.tg tr td:nth-child(' + (i) + ')').css('left', intLeft); } }; for (var i = 1; i <= intRow; i++) { $('.tg tr:nth-child(' + i + ')').find('td').css('z-index', '2').css('color', 'purple'); if (i == 1) { $('.tg tr:nth-child(1)').find('td').css('top', '0px'); } else { var intTop = parseFloat($('.tg tr:nth-child(' + (i - 1) + ')').find('td').css('top').replace('px', '')) + parseFloat($('.tg tr:nth-child(' + (i - 1) + ')').find('td').css('height').replace('px', '')) + 20 + 'px'; //20=上+下padding console.log(i + ':' + intTop); $('.tg tr:nth-child(' + i + ')').find('td').css('top', intTop); } $('.tg tr:nth-child(' + i + ')').each(function() { $(this).find('td:nth-child(-n+' + intCol + ')').css('z-index', '3') }) } } ``` --> --- ## 參考 1. [純CSS實現表格首行和首列固定](https://www.astralweb.com.tw/pure-css-implementation-table-headers-columns-fixed/) 2. [Sticky position](https://ithelp.ithome.com.tw/articles/10241079) 3. [Sticky table head pure css凍結表頭純CSS](https://codepen.io/FernHsu/pen/bGGXWdO) 4. [box-shadow - CSS](https://developer.mozilla.org/zh-TW/docs/Web/CSS/box-shadow) ## 其他工具 1. [表格產生工具](https://www.tablesgenerator.com/html_tables) 設定好表格後即可生成html代碼或直接另存成檔案 2. [html格式整理工具](https://www.10bestdesign.com/dirtymarkup/) 輕鬆排版!