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>
相关推荐
速盾cdn31 分钟前
速盾:网页游戏部署高防服务器有什么优势?
服务器·前端·web安全
小白求学132 分钟前
CSS浮动
前端·css·css3
什么鬼昵称33 分钟前
Pikachu-csrf-CSRF(POST)
前端·csrf
golitter.1 小时前
Vue组件库Element-ui
前端·vue.js·ui
儒雅的烤地瓜1 小时前
JS | JS中判断数组的6种方法,你知道几个?
javascript·instanceof·判断数组·数组方法·isarray·isprototypeof
道爷我悟了1 小时前
Vue入门-指令学习-v-on
javascript·vue.js·学习
27669582921 小时前
京东e卡滑块 分析
java·javascript·python·node.js·go·滑块·京东
golitter.1 小时前
Ajax和axios简单用法
前端·ajax·okhttp
PleaSure乐事1 小时前
【Node.js】内置模块FileSystem的保姆级入门讲解
javascript·node.js·es6·filesystem
雷特IT2 小时前
Uncaught TypeError: 0 is not a function的解决方法
前端·javascript