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>
相关推荐
爱泡脚的鸡腿20 分钟前
uni-app D3实战(小兔仙)
前端
嬉皮客31 分钟前
Gird布局详解
前端·css
烛阴31 分钟前
C#常量(const)与枚举(enum)使用指南
前端·c#
Wect34 分钟前
学习React-DnD:实现多任务项拖拽-useDrag处理
前端
mucheni42 分钟前
迅为RK3568开发板OpeHarmony学习开发手册-修改应用程序名称
linux·前端·学习
WebGirl44 分钟前
SSE服务
前端
Mintopia1 小时前
🛰️ 低带宽环境下的 AIGC 内容传输优化技术
前端·人工智能·trae
h***34631 小时前
Nginx 缓存清理
android·前端·后端
Mintopia1 小时前
⚡Trae Solo Coding 的效率法则
前端·人工智能·trae
wa的一声哭了1 小时前
WeBASE管理平台部署-WeBASE-Web
linux·前端·网络·arm开发·spring boot·架构·区块链