表格固定表头

        今天折腾个东东,想要把表格的表头固定,很多网站都有这样的浏览体验,所以也给自己加个。在网上搜索好多,不清不楚,不知所云,还不如自己写一个。既然自己写就得整理一下思路。

        其实只需要把表头位置放到浏览器的可视区域顶部就行,表格的其它部分不需要控制。所以很简单,代码如下:

 1   function tableProperty(id){
 2     //var tbls = document.getElementsByTagName("table");
 3     //this.tbl = tbls && tbls.length && tbls[0];
 4     if(!id) return;
 5     this.tbl = document.getElementById(id);
 6     this.th = this.tbl && this.tbl.tHead;
 7     this.tb = this.tbl && this.tbl.tBody;
 8   };
 9   tableProperty.prototype.init=function(){
10     if(!this.th) return;
11     this.initTop = this.th.offsetTop;
12     var that = this;
13     if(window.attachEvent){//IE
14       window.attachEvent("onscroll",function(){
15       that.onScroll();
16       },false);
17     }
18     else if(window.addEventListener){//modern browsers
19       window.addEventListener("scroll",function(){
20         that.onScroll();
21       },false);
22     }
23     else{
24     }
25   };
26   tableProperty.prototype.onScroll = function(){
27     if(typeof this.initTop!="number"||!this.th) return;
28     if(this.initTop>window.scrollY){
29       this.th.style.top = this.initTop - window.scrollY;
30     }
31     else{
32       this.th.style.top = 0;
33     }
34   };

使用方法:

1 var tp = new tableProperty("fixTable");
2 tp.init();

"fixTable"为表格id,直接使用就OK了。

差点忘记了,表格的thead中,position要设置为fixed^_^

posted @ 2013-12-09 21:46  月窟仙人  阅读(236)  评论(0编辑  收藏  举报