thread置顶

225 阅读1分钟

一、背景

table里有很长的数据,希望滚动时,可以将thead置顶。

二、方法

方式1:position:sticky 粘性布局

【核心代码】

thead {
      th {   // 必须放到thposition: sticky;
        top: 0;
        background: #f5f5f5;
        color: #676A78;
        line-height: 50px;
        height: 50px;
      }
}

【优点】 实现简单,文档没有脱离文档流样式保留
【缺点】 兼容性差
【结论】 不推荐使用

方式2:计算距离+position:fixed

【核心代码】

if (this.$el.querySelector('table').getBoundingClientRect().top< 0) {
     activity = true ; // 样式
 } else {
     activity = true ;
 }

【优点】 兼容性好 【缺点】
postiotn:fixed 导致元素脱离文档流,使得原先的table的样式失效,需要人工去写一遍和thead一样的样式。
【结论】 不推荐使用

方式3:计算距离+transform

【核心代码】

 <table>
        <thead>
          <tr>
            <th v-for="(item, index) in tableItemList" :key="index">{{ item }}</th>
          </tr>
        </thead>

        <tbody>
        ...
        </tbody>
</table>

// js
mounted () {
    // 表头置顶
    this.$nextTick(function() {
     // 初始化的时候监听scoll事件
      window.addEventListener('scroll', this.handleScroll)
    })
  },

  
 methods: {
    handleScroll () {
      const top = this.$el.querySelector('table').getBoundingClientRect().top; // 要计算的是table到视窗的高度,因此不改变
      this.$el.querySelector('thead').style.transform = 'translateY(' + (top < 0 ? -top : 0) + 'px)'
    },
  },

   destroyed () {
    // 离开该页面需要移除这个监听的事件
    window.removeEventListener('scroll', this.handleScroll)
  },

【优点】 不脱离文档流,无需重写样式。实现简单。
【缺点】无
【结论】采用