Vue多种方法实现表头和首列固定的示例代码


Posted in Javascript onFebruary 02, 2018

有时表格太大,滚动时信息查看不方便,需要对表格进行全局表头、首列固定,

上效果:

Vue多种方法实现表头和首列固定的示例代码

一、创建多个表格进行覆盖

思路:当页面滚动到临界值时,出现固定表头、首列

先创建一个活动表格

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
      th,
      td {
        min-width: 200px;
        height: 50px;
      }
      #sTable {
        margin-top: 300px
      }
      [v-cloak]{
        display: none;
      }
    </style>
  </head>
  <body v-cloak>
    <!--活动的表格-->
    <table id="sTable" border="1" cellspacing="0">
      <thead>
        <tr>
          <th v-for="item in th">{{item.key}}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in tl">
          <td v-for="list in item">{{list.key}}</td>
        </tr>
      </tbody>
    </table>
    <script src="vue.js"></script>
    <script src="jquery.js"></script>
    <script>
      var vm = new Vue({
        el: "body",
        data: function() {
          return {
            th: [],
            tl: [],
            temp: [],
          }
        },
        methods: {
          //生成表格
          CTable: function() {
            for(var i = 0; i < 10; i++) {
              this.th.push({
                key: "head" + i
              })
            }
            for(var i = 0; i < 100; i++) {
              for(var j = 0; j < 10; j++) {
                this.temp.push({
                  key: j + "body" + i
                })
              }
              this.tl.push(this.temp)
              this.temp = []
            }
          },
        },
        ready: function() {
          this.CTable();
        },
      })
    </script>
  </body>
</html>

再添加固定表头:

#fHeader {
  background: lightblue;
  position: fixed;
  top: 0;
}
<!--固定表头-->
<table border="1" id="fHeader" cellspacing="0" v-show="fixedHeader"> 
  <thead>
    <tr >
      <th v-for="item in th">{{item.key}}</th>
    </tr>
  </thead>
</table>

监控表格位置到达窗口顶部时出现固定表头

//监控表头位置
headerMonitor:function(){
  var self=this
  var hHeight=$("#sTable").offset().top;
  $(document).scroll(function(){
    //当滚动条达到偏移值的时候,出现固定表头
    if($(this).scrollTop()>hHeight){
      self.fixedHeader=true
    }else{
      self.fixedHeader=false
    }

  })
}

当然需要调用该方法

ready: function() {
  this.CTable();
  this.headerMonitor()
},

然后添加固定首列以及固定的A1单元格

#fHeader {
  background: lightblue;
    position: fixed;
    top: 0;
    z-index: 1;
  }
  .fixedA1{
    background: lightblue;
    position: fixed;
    top: 0;
    left: 0;
    z-index:2;
  }
<!--固定A1-->
<table border="1" cellspacing="0" class="fixedA1" v-show="fixedA1">
  <thead>
    <tr>
      <th v-for="item in th" v-if="$index==0">{{item.key}}</th>
    </tr>
  </thead>
</table>
<!--固定首列-->
<table border="1" cellspacing="0" class="fixedCol" v-show="fixedCol">
  <thead>
    <tr>
      <th v-for="item in th" v-if="$index==0">{{item.key}}</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="item in tl">
      <td v-for="list in item" v-if="$index==0">{{list.key}}</td>
    </tr>
  </tbody>
</table >

同理监控表格的位置

//监控表头、首列位置
monitor:function(){
  var self=this
  $(document).scroll(function(){
    self.setPosition()
    //当滚动条达到左偏移值的时候,出现固定列头
    if($(this).scrollLeft()>self.hLeft){
      self.fixedCol=true
    }else{
      self.fixedCol=false
    }
    //当滚动条达到上偏移值的时候,出现固定表头
    if($(this).scrollTop()>self.hHeight){
      self.fixedHeader=true
    }else{
      self.fixedHeader=false
    }
    //当表格移到左上角时,出现固定的A1表格
    if($(this).scrollLeft()>self.hLeft&&$(this).scrollTop()>self.hHeight){
      self.fixedA1=true
    }else{
      self.fixedA1=false
    }
  })
},

因为表格的移动会影响表头的位置的定位位置,因此需要将当前表格的偏移值赋给固定表头。首列

setPosition:function(){
  $("#fHeader").css("left",this.hLeft-$(document).scrollLeft())
  $(".fixedCol").css("top",this.hHeight-$(document).scrollTop())
}

二、控制样式实现固定表头,首列

思路:当表格达到临界值时,改变表头,首列的样式

首先实现表头固定

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
      th,
      td {
        min-width: 200px;
        height: 50px;
      }
      table {
        margin: 300px
      }
      .fHeader {
        background: lightblue;
        position: fixed;
        top: 0;
      }
      [v-cloak]{
        display: none;
      }
    </style>
  </head>
  <body v-cloak>
    <table border="1" cellspacing="0">
      <thead>
        <tr :class="{fHeader:fixedHeader}">
          <th v-for="item in th">{{item.key}}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in tl">
          <td v-for="list in item">{{list.key}}</td>

        </tr>
      </tbody>
    </table>
    <script src="vue.js"></script>
    <script src="jquery.js"></script>
    <script>
      var vm = new Vue({
        el: "body",
        data: function() {
          return {
            th: [],
            tl: [],
            temp: [],
            fixedHeader: false,
          }
        },
        methods: {
          //生成表格,代码相同,省略
          CTable: function() {},
          //监控表头位置
          headerMonitor:function(){
            var self=this
            var hHeight=$("table").offset().top;
            $(document).scroll(function(){
              //当滚动条达到偏移值的时候,出现固定表头
              if($(this).scrollTop()>hHeight){
                self.fixedHeader=true
              }else{
                self.fixedHeader=false
              }
            })
          }
        },
        ready: function() {
          this.CTable();
          this.headerMonitor()
        },
      })
    </script>
  </body>
</html>

添加固定首列

.fixedCol>:first-child{
  background: lightblue;
  position: fixed;
  z-index: 1;
  border:1px solid grey;
  left: 0;
  line-height: 50px;
}

监控表格位置

//监控表头,首列位置
monitor:function(){
  this.setPosition()
  var self=this
  $(document).scroll(function(){
    self.setPosition();
    //当滚动条达到偏移值的时候,出现固定表头
    if($(this).scrollTop()>self.hHeight){
      self.fixedHeader=true;
    }else{
      self.fixedHeader=false
    }
    //当滚动条达到左偏移值的时候,出现固定列头
    if($(this).scrollLeft()>self.hLeft){
      self.fixedCol=true
    }else{
      self.fixedCol=false
    }
    //当表格移到左上角时,出现固定的A1表格
    if($(this).scrollLeft()>self.hLeft&&$(this).scrollTop()>self.hHeight){
      self.fixedA1=true
    }else{
      self.fixedA1=false
    }
  })
},

设置偏移值

//使固定表头与列头的偏差与当前表格的偏移值相等
setPosition:function(){
  $(".fixedHeader").css("left",this.hLeft-$(document).scrollLeft())
  for(var i=0,len=this.tl.length+1;i<len;i++){
    //因为设置了“border-collapse:collapse”,所以要加“54-1”
    $(".fixedCol>:first-child").eq(i).css("top",this.hHeight-$(document).scrollTop()+53*i)
  }
}

因为当表头变成fixed定位时会脱离文档流,表格的第二行会被隐藏,所以需要多第二列进行宽高的拓展

/*因为fixed定位不占位,当固定表头出现时,有一行会补到表头位置,即有一行跳空,将tbody的第一行行高加倍*/
.fixedHeaderGap:first-child>td{
    padding-top:54px;
  }
/*因为fixed定位不占位,当固定列头出现时,有一列会补到列头位置,即有一列跳空,将tbody的第二列p设置padding*/
.fixedCol>:nth-child(2){
  padding-left: 205px;
}

当再次浏览器打开时该页面时,需要监控表格是否还达到固定表头的临界条件

watch:{
  //页面初始加载时,使固定表头与列头的偏差与当前表格的偏移值相等
  "fixedHeader":function(){
    this.setPosition()
  },
  "fixedCol":function(){
    this.setPosition()
  },
},

三、Vue自定义指令实现滚动监听

当使用vue时,就很少会用到Jq这么庞大的库,而且vue官方也不推荐操作Dom元素,因此可以自定义指令实现固定表头,首列。本文用的是Vue.js v1.0.26,但V2.0的思路其实也一样。

直接上代码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
      th,
      td {
        min-width: 200px;
        height: 50px;
      }
      #sTable {
        margin: 300px
      }
      .fixedCol{
        position: fixed;
        left: 0;
        background: lightblue;
        z-index: 1;
      }
      #fHeader {
        background: lightblue;
        position: fixed;
        top: 0;
        z-index: 1;
      }
      .fixedA1{
        background: lightblue;
        position: fixed;
        top: 0;
        left: 0;
        z-index:2;
      }
      [v-cloak]{
        display: none;
      }
    </style>
  </head>
  <body v-cloak>
    <!--固定A1-->
    <table border="1" cellspacing="0" class="fixedA1" v-show="fixedA1">
      <thead>
        <tr>
          <th v-for="item in th" v-if="$index==0">{{item.key}}</th>
        </tr>
      </thead>
    </table>
    <!--固定列头-->
    <table border="1" cellspacing="0" class="fixedCol" v-show="fixedCol">
      <thead>
        <tr>
          <th v-for="item in th" v-if="$index==0">{{item.key}}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in tl">
          <td v-for="list in item" v-if="$index==0">{{list.key}}</td>
        </tr>
      </tbody>
    </table >
    <!--固定表头-->
    <table border="1" id="fHeader" cellspacing="0" v-show="fixedHeader"> 
      <thead>
        <tr >
          <th v-for="item in th">{{item.key}}</th>
        </tr>
      </thead>
    </table>
    <!--活动的表格,绑定自定义指令-->
    <table id="sTable" border="1" cellspacing="0" v-scroll>
      <thead>
        <tr>
          <th v-for="item in th">{{item.key}}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in tl">
          <td v-for="list in item">{{list.key}}</td>
        </tr>
      </tbody>
    </table>
    <script src="vue.js"></script>
    <script>
      var vm = new Vue({
        el: "body",
        data: function() {
          return {
            th: [],
            tl: [],
            temp: [],
            fixedCol: false,
            fixedHeader:false,
            fixedA1:false,
            hLeft:0,
            hHeight:0,
          }
        },
        directives:{
          scroll:{
            bind:function(){
              //触发滚动监听事件
              window.addEventListener('scroll',function(){
                this.vm.monitor()
              })
            }
          }
        },
        methods: {
          //生成表格
          CTable: function() {},
          //监控表头、列头位置
          monitor:function(){
            this.setPosition();
            //当滚动条达到左偏移值的时候,出现固定列头
            if(document.body.scrollLeft>this.hLeft){
              this.fixedCol=true;
            }else{
              this.fixedCol=false;
            }
            //当滚动条达到上偏移值的时候,出现固定表头
            if(document.body.scrollTop>this.hHeight){
              this.fixedHeader=true;
            }else{
              this.fixedHeader=false;
            }
            //当表格移到左上角时,出现固定的A1表格
            if(document.body.scrollLeft>this.hLeft&&document.body.scrollTop>this.hHeight){
              this.fixedA1=true;
            }else{
              this.fixedA1=false;
            }
          },
          //使固定表头与列头的偏差与当前表格的偏移值相等
          setPosition:function(){
            document.getElementById("fHeader").style.left=this.hLeft-document.body.scrollLeft+"px";
            document.getElementsByClassName("fixedCol")[0].style.top=this.hHeight-document.body.scrollTop+"px";
          },
        },
        ready: function() {
          this.CTable();
          this.hLeft=document.getElementById("sTable").offsetLeft;
          this.hHeight=document.getElementById("sTable").offsetTop
          this.monitor()
        },
      })
    </script>
  </body>
</html>

若想要做成自定义回调事件,可以用eval(),

<table id="sTable" border="1" cellspacing="0" v-scroll="monitor">
directives:{
  scroll:{
    bind:function(){
      var self=this;
      //触发滚动监听事件
      window.addEventListener('scroll',function(){
        //触发滚动回调事件
        eval("self.vm."+self.expression)()
      })
    }
  }
},

自定义回调指令固定表列头.html 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
改进:论坛UBB代码自动插入方式
Dec 22 Javascript
Prototype源码浅析 String部分(一)之有关indexOf优化
Jan 15 Javascript
js实现点击向下展开的下拉菜单效果代码
Sep 01 Javascript
基于JavaScript实现图片点击弹出窗口而不是保存
Feb 06 Javascript
使用jQuery或者原生js实现鼠标滚动加载页面新数据
Mar 06 Javascript
js弹出窗口返回值的简单实例
May 28 Javascript
JS Ajax请求如何防止重复提交
Jun 13 Javascript
关于微信中a链接无法跳转问题
Aug 02 Javascript
浅谈javascript的url参数parse和build函数
Mar 04 Javascript
angular4自定义组件非input元素实现ngModel双向数据绑定的方法
Dec 28 Javascript
Vue项目服务器部署之子目录部署方法
May 12 Javascript
vue实现简单的登录弹出框
Oct 26 Javascript
jquery.picsign图片标注组件实例详解
Feb 02 #jQuery
使用webpack打包koa2 框架app
Feb 02 #Javascript
Vue组件化开发思考
Feb 02 #Javascript
微信小程序实现导航栏选项卡效果
Jun 19 #Javascript
解析Vue.js中的组件
Feb 02 #Javascript
如何将你的AngularJS1.x应用迁移至React的方法
Feb 01 #Javascript
vue 2.0 购物车小球抛物线的示例代码
Feb 01 #Javascript
You might like
php Sql Server连接失败问题及解决办法
2009/08/07 PHP
php用正则表达式匹配URL的简单方法
2013/11/12 PHP
JavaScript判断两种格式的输入日期的正确性的代码
2007/03/25 Javascript
Extjs中常用表单介绍与应用
2010/06/07 Javascript
JavaScript学习点滴 call、apply的区别
2010/10/22 Javascript
jQuery 1.5.1 发布,全面支持IE9 修复大量bug
2011/02/26 Javascript
推荐40个非常优秀的jQuery插件和教程【系列三】
2011/11/09 Javascript
node.js中的fs.stat方法使用说明
2014/12/16 Javascript
jquery zTree异步加载简单实例讲解
2016/02/25 Javascript
Bootstrap表格和栅格分页实例详解
2016/05/20 Javascript
详解PHP中pathinfo()函数导致的安全问题
2017/01/05 Javascript
js实现省份下拉菜单效果
2017/02/15 Javascript
nodejs服务搭建教程 nodejs访问本地站点文件
2017/04/07 NodeJs
Node.js中看JavaScript的引用
2017/04/22 Javascript
AngularJs的UI组件ui-Bootstrap之Tooltip和Popover
2018/07/13 Javascript
小程序采集录音并上传到后台
2019/11/22 Javascript
[58:21]DOTA2亚洲邀请赛 4.3 突围赛 Liquid vs VGJ.T 第二场
2018/04/04 DOTA
[06:48]DOTA2-DPC中国联赛2月26日Recap集锦
2021/03/11 DOTA
python实现html转ubb代码(html2ubb)
2014/07/03 Python
用Python从零实现贝叶斯分类器的机器学习的教程
2015/03/31 Python
Python HTML解析器BeautifulSoup用法实例详解【爬虫解析器】
2019/04/05 Python
Python 一键获取百度网盘提取码的方法
2019/08/01 Python
关于numpy数组轴的使用详解
2019/12/05 Python
pycharm第三方库安装失败的问题及解决经验分享
2020/05/09 Python
python实现计算图形面积
2021/02/22 Python
html5的input的required使用中遇到的问题及解决方法
2018/04/24 HTML / CSS
高清安全摄像头系统:Lorex Technology
2018/07/20 全球购物
高三自我鉴定怎么写
2013/10/19 职场文书
旅游项目开发策划书
2014/01/18 职场文书
舞蹈毕业生的自我评价
2014/03/05 职场文书
2014教师党员自我评议总结
2014/09/19 职场文书
大学生就业协议书范本(适用于公司企业)
2014/10/07 职场文书
元旦标语大全
2014/10/09 职场文书
财务工作失误检讨书
2015/02/19 职场文书
解决Navicat for Mysql连接报错1251的问题(连接失败)
2021/05/27 MySQL
关于MySQL中explain工具的使用
2023/05/08 MySQL