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

  • 相关阅读:
    border-sizing属性详解和应用
    初识scss:配置与运行
    详解scss的继承、占位符和混合宏
    详解promise、async和await的执行顺序
    JS调用模式
    自已写的线程池
    ThreadPool.QueueUserWorkItem的用法
    C#定时执行
    Task.Factory.StartNew的用法
    C#写文本日志帮助类(支持多线程)改进版(不适用于ASP.NET程序)
  • 原文地址:https://www.cnblogs.com/mike442144/p/3466162.html
Copyright © 2011-2022 走看看