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>
相关推荐
ᥬ 小月亮2 分钟前
webpack基础
前端·webpack
YongGit21 分钟前
探索 AI + MCP 渲染前端 UI
前端·后端·node.js
慧一居士1 小时前
<script setup>中的setup作用以及和不带的区别对比
前端
RainbowSea1 小时前
NVM 切换 Node 版本工具的超详细安装说明
java·前端
读书点滴1 小时前
笨方法学python -练习14
java·前端·python
Mintopia2 小时前
四叉树:二维空间的 “智能分区管理员”
前端·javascript·计算机图形学
慌糖2 小时前
RabbitMQ:消息队列的轻量级王者
开发语言·javascript·ecmascript
Mintopia2 小时前
Three.js 深度冲突:当像素在 Z 轴上玩起 "挤地铁" 游戏
前端·javascript·three.js
Penk是个码农2 小时前
web前端面试-- MVC、MVP、MVVM 架构模式对比
前端·面试·mvc
MrSkye2 小时前
🔥JavaScript 入门必知:代码如何运行、变量提升与 let/const🔥
前端·javascript·面试