Element table 表头吸顶效果(适用于表头无fixed属性使用)

在 main.js 自定义 sticky 指令

Vue.directive('sticky', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted(el,binding) {
    // 获取表格
    const thead = el.children[1]
    const tbody = el.children[2]
    // 获取滚动元素
    const scrollParent = document.querySelector(binding.value.parent)
    scrollParent.addEventListener('scroll', function(){
      // 获取thead距离顶部的距离
      let theadTop = thead.getBoundingClientRect().top
      if (theadTop <= binding.value.top) {
        thead.style.position = 'fixed'
        thead.style.zIndex = '2021'
        thead.style.top = binding.value.top + 'px'
        thead.style.width = tbody.offsetWidth + 'px'
      }
      // 判断是否需要回归原来位置
      let originally = tbody.getBoundingClientRect().top
      if (originally > binding.value.top) {
        thead.style.position = 'relative'
        thead.style.zIndex = '0'
        thead.style.top = 0 + 'px'
        thead.style.width = tbody.offsetWidth + 'px'
      }
      // 判断底部距离是否超过表头
      let goBeyond =tbody.getBoundingClientRect().bottom
      if (goBeyond <= thead.offsetHeight) {
        thead.style.position = 'relative'
        thead.style.zIndex = '0'
        thead.style.top = 0 + 'px'
        thead.style.width = tbody.offsetWidth + 'px'
      }
    })
  },
})

使用方法,top 为距离顶部位置,parent 滚动元素 ID

template>
    <el-table
    	v-sticky="{top: 150,parent:'#table_box'}"
      :data="tableData"
      style="width: 100%">
      <el-table-column
        prop="date"
        label="日期"
        width="180">
      </el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址">
      </el-table-column>
    </el-table>
  </template>
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值