一次element表格高度问题的记录

447 阅读1分钟

一个关于高度的问题

本文只用于个人记录

今天是妇女节 各位小姐姐节日快乐呀

前端增删改查员又来改bug了呀

背景: 一个简单的增删改查页面, 上面是搜索区域, 下面是分页, 中间夹个表格

产品要求如下, table 要在中间自适应

image.png

思路

这种中间自适应的需求也很常见, 这里选择了用 fixed 然后加上 top 和 bottom 来进行实现

.fixed-container {
  position: fixed;
  top: 260px;
  left: 240px;
  right: 0px**;**
  bottom: 60px;
  overflow: auto;
}

问题

container 是满足了这个条件, 但是出现了如下图的问题, 黑色部分代表滚动条的位置

  1. 只有拉到底才能看到底部滚动条, 当表格较长时候, 不满足需求
  2. 表头会随着垂直滚动条滚动, 产品希望表头固定

image.png

解决

其实只要给 element 的 table 设置 height属性 就好, 重点在于中间的区域因为电脑屏幕大小不同是不一样的, 所以需要动态获取, 然后赋值给表格

在获取高度的时候不由得感叹, 如果平时不怎么用这些 api, 用的时候还是有点费劲的

  getTableHeight () {
    const containerHeight = document.querySelector('.fixed-container').offsetHeight
    const paddingTop = parseInt(window.getComputedStyle(document.querySelector('.fixed-container')).paddingTop)
    const paddingBottom = parseInt(window.getComputedStyle(document.querySelector('.fixed-container')).paddingBottom)
    const marginTop = parseInt(window.getComputedStyle(document.querySelector('.table')).marginTop)
    const marginBottom = parseInt(window.getComputedStyle(document.querySelector('.table')).marginBottom)
    this.tableHeight = containerHeight - paddingTop - paddingBottom - marginTop - marginBottom + 'px'
  },
      
      
    mounted () {
    // 如果要做的完善一点 需要再加上 对 resize 事件的监听
      this.getTableHeight()
    }
    

template 代码如下, 这里使用了 v-if 是为了等高度计算好再渲染 table, 不然是无效的

<div class="fixed-container">
  <div class="table">
    <egrid
      v-if="tableHeight"
      :height="tableHeight"
      stripe
      border
      column-type="index"
      :columns="config"
      :data="tableData"
      v-loading="loading"
      @selection-change="(val) => handleSelectionChange(val)"
    >
    </egrid>
  </div>
</div>