js固定表头的实现(转)
原文鏈接:http://www.th7.cn/web/js/201509/121055.shtml
參考鏈接:http://www.jb51.net/article/102568.htm
寫兩個表格,一個為表頭,另一個為表內容。當表內容數據量比較大時,可以直接在表內容所在的父容器進行滾動。以下為demo代碼實現:
<table> <thead class="header"> <tr><th>姓名</th><th>愛好</th> </tr> </thead></table><div id='scrollContainer' ><table class="table" cellspacing=0 cellpadding=0 id="mytable"><tbody><tr> <td>一介碼妞</td><td>吉他</td></tr></tbody></table></div><!-- 以下的js只是為了批量生成數據,真正固定表頭的方法是fixTabHeader --><script type="text/javascript">$(document).ready(function(){ var row=$("#mytable >tbody>tr:first"); for(i=0;i<80;i++){$('table#mytable > tbody').append(row.clone()); } $("#mytable").fixedHeader(); });</script>
<script type="text/javascript">function fixTabHeaderScroll(tabid){ var $parent,$head,pTop,oTop,headTop,o;o=$("#"+tabid);oTop=o.height();$parent=o.parent();pTop=$parent.height();$head=$parent.prev();if (pTop <=oTop) {$head.css({$head.outerWidth(true)-scrollBarWidth+"px"});}else{$head.css({100+"%"});}}</script>
分析
這種方式應該是最簡單,最明了的實現方式,表頭和表內容分家,各管各家,對于表頭來說,不管表內容滾或者不滾,它都在哪里不離不棄。但是存在一個問題,在表內容沒有滾動時,表頭和表身是垂直對齊的,一旦表身出現滾動,新出現的滾動條會占用表身的部分寬度,這就導致表身和表頭又不對齊。所以,我們需要在給兩個表格應用同樣樣式的基礎上,再用js函數控制兩個的寬度,使他們寬度一致,大體思路是獲取滾動條的寬,然后設置表頭的寬度減去滾動條的寬度。
補充介紹Jquery的幾個參數:
offsetWidth :當前對象的的寬度包括滾動條在內
scrollWidth :當前對象的滾動寬度不包括滾動條在內
在css的盒子模型中,最內部是content,然后是padding、border、margin
width=content
innerWidth = width + padding
outerWidth = innerWidth + border
outerWidth(true) = outerWidth + margin
關于outerWidth屬性有一個傳入參數可以控制它包不包含外部的margin 為true的話包含,默認不包含。
注意:要想表格相對于某個父容器做數據滾動,則該父容器必須做如下設置:
(1)設置固定高度,不設置高度或者用百分比設置高度,滾動不起作用
(2)設置屬性overflow-y:auto
必選項,否則當表格數據過多時,不會產生滾動條,而是自動延長該父容器的高度
(3)設置 position:relative;
若不設置,拷貝得來的表頭將相對于其設置該屬性為該值的父節點(或間接父節點)定位,如果沒有,則相對于body
我的代碼:
<html> <head> <title>test scrollTop</title> <style type="text/css"> #ttitle{ width:100px; border:1px solid blue; height:27px; } #tcontent{ width:100px; border:1px solid red; height:100px; overflow:auto; } tr{ height:20px; } table{ width:100px; border:1px solid black; } </style> <script type="text/javascript"> </script> </head> <body> <div id="ttitle"> <table> <th>姓名</th> <th>年齡</th> </table> </div> <div id="tcontent"> <table> <tr> <td>guo</td> <td>21</td> </tr> <tr> <td>guo</td> <td>21</td> </tr> <tr> <td>guo</td> <td>21</td> </tr> <tr> <td>guo</td> <td>21</td> </tr> <tr> <td>guo</td> <td>21</td> </tr> <tr> <td>guo</td> <td>21</td> </tr> <tr> <td>guo</td> <td>21</td> </tr> <tr> <td>guo</td> <td>21</td> </tr> </table> </div> </body> </html>
總結
以上是生活随笔為你收集整理的js固定表头的实现(转)的全部內容,希望文章能夠幫你解決所遇到的問題。