zoukankan      html  css  js  c++  java
  • 表格固定表头

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

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

     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^_^

  • 相关阅读:
    17-canvas绘制扇形
    16-canvas绘制圆弧
    15-canvas渐变色
    14-canvas绘制柱状图
    13-绘制矩形的简写方式
    12-es6类的方式封装折线图
    11-canvas绘制折线图
    10-canva绘制数据点
    jenkins 环境部署 (yum安装方式)
    BerkeleyDB安装
  • 原文地址:https://www.cnblogs.com/mike442144/p/3466162.html
Copyright © 2011-2022 走看看