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

编程入门 行业动态 更新时间:2024-10-21 10:04:48

getBoundingClientRect使用场景(table固定<a href=https://www.elefans.com/category/jswz/34/1762281.html style=表头)"/>

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

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

<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为例,分装通用组件 

<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.paddingthis.height = hdiffthis.warpStyle = {height: hdiff + 'px'}}, 200)})}},destroyed() {window.removeEventListener('resize', this.initHeight)}
}
</script><style scoped>
.warp-body {width: 100%;
}
</style>

更多推荐

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

本文发布于:2023-12-05 18:38:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1664981.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表头   场景   getBoundingClientRect   table

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!