getBoundingClientRect使用场景(table固定表头)

  • getBoundingClientRect()用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置,是DOM元素到浏览器可视范围的距离(不包含文档scroll的部分)。
  • 该函数返回一个Object对象,该对象有6个属性:top,lef,right,bottom,width,height

javascript 复制代码
<div id="box"></div>
var object=document.getElementById('box');  
rectObject = object.getBoundingClientRect();
rectObject.top:元素上边到视窗上边的距离;
rectObject.right:元素右边到视窗左边的距离;
rectObject.bottom:元素下边到视窗上边的距离;
rectObject.left:元素左边到视窗左边的距离;
rectObject.width:是元素自身的宽 (包括滚动条)
rectObject.height是元素自身的高 (包括滚动条)

使用场景:在使用框架进行开发是,经常会遇到需要给table固定表头的需求,这时候需要给table设置一个固定的高度,可以使用添加一个元素通过getBoundingClientRect计算top的距离,然后获取浏览器可视范围高度,进行计算

下面以VUE为例,分装通用组件

javascript 复制代码
<template>
  <div ref="warp_body" class="warp-body" :style="warpStyle">
    <slot :height="height" />
  </div>
</template>
<script>
/*
  * @doc 自动获取元素剩下的高度, 在列表中科院很好的使用
  * @props { padding: Number } 底下的高度
   <AutofixHeight :padding="100">
     <template slot-scope="{height}">
      <Table :height="height" />
    </template>
   </AutofixHeight>
  * */
export default {
  name: 'AutofixHeight',
  props: {
    padding: {
      type: Number,
      default: 78
    }
  },
  data() {
    return {
      warpStyle: {
        height: '200px'
      },
      height: 0
    }
  },
  mounted() {
    this.initHeight()
    window.addEventListener('resize', this.initHeight)
  },
  methods: {
    initHeight() {
      // 初始化获取组件当前所在的位置
      this.$nextTick(() => {
        setTimeout(() => {
          //表格高度 = 浏览器可视范围高度 - 距离顶部高度 - 其它高度
          const hdiff = document.body.clientHeight - this.$refs.warp_body.getBoundingClientRect().top - this.padding
          this.height = hdiff
          this.warpStyle = {
            height: hdiff + 'px'
          }
        }, 200)
      })
    }
  },
  destroyed() {
    window.removeEventListener('resize', this.initHeight)
  }
}
</script>

<style scoped>
.warp-body {
  width: 100%;
}
</style>
相关推荐
We་ct4 分钟前
LeetCode 39. 组合总和:DFS回溯解法详解
前端·算法·leetcode·typescript·深度优先·个人开发·回溯
yeshihouhou5 分钟前
redisson实现延迟队列
java·前端·数据库
明码10 分钟前
Pathlib库
java·服务器·前端
吴声子夜歌11 分钟前
小程序——界面API(二)
前端·小程序
im_AMBER1 小时前
编辑器项目开发复盘:主题切换
前端·学习·前端框架·编辑器·html5
我命由我123452 小时前
React - 验证 Diffing 算法、key 的作用
javascript·算法·react.js·前端框架·html·html5·js
@PHARAOH4 小时前
HOW - Kratos 入门实践(二)- 概念学习
前端·微服务·go
We་ct8 小时前
LeetCode 77. 组合:DFS回溯+剪枝,高效求解组合问题
开发语言·前端·算法·leetcode·typescript·深度优先·剪枝
KerwinChou_CN8 小时前
什么是流式输出,后端怎么生成,前端怎么渲染
前端
爱上妖精的尾巴8 小时前
8-18 WPS JS宏 正则表达式-边界匹配
开发语言·javascript·正则表达式·wps·jsa