适用场景:在网页表格中我们需要获取页面剩余高度来为表格做滚动的时候就需要使用响应高度,可以使用原生calc来计算,但是calc有个缺陷就是,有可能要去计算多个盒子高度,使用下面的代码就可以直接获取当前元素到顶部的距离,然后减去总高度即可,是相当的方便 。
TS端代码:
import { ref , onMounted } from "vue";
/*
*
* Vue3计算剩余高度
*
*/
export default function () {
//在Init的时候先行调用,然后在监听窗口的变化,保证是最新的宽高度
onMounted(()=>{
setWindowResize();
window.addEventListener('resize',setWindowResize)
});
//测算基点
let basePoint = ref();
//元素测试盒子
let elementToTopHight = ref(0);
//窗口的高度
let windowHeight = ref(0);
const setWindowResize = function () {
elementToTopHight.value = basePoint.value.getBoundingClientRect().top;
windowHeight.value = window.innerHeight
}
return { basePoint , elementToTopHight , windowHeight };
}
页面端代码:
<script setup lang="ts">
import useCommon from '@/common/useCommon';
const { basePoint , windowHeight , elementToTopHight } = useCommon();
</script>
<template>
<div id="app">
<div style="height: 30px;background-color: rosybrown">{{ elementToTopHight }}</div>
<div ref="basePoint"></div>
<div :style="`height:calc( ${ windowHeight } - ${ elementToTopHight }px);background-color: tan`"></div>
</div>
</template>
<style>
html, body, #app {
height: 100vh;
width: 100vw;
margin: 0;
padding: 0;
background-color: rebeccapurple;
}
</style>
微信小程序(Uniapp):
//获取屏幕的总高度
export function getScreenHeight() : number {
let platform = uni.getSystemInfoSync().uniPlatform;
if(platform == 'mp-weixin') {
//微信小程序需要减去顶部的statusBarHeight
return uni.getSystemInfoSync().windowHeight - uni.getSystemInfoSync().statusBarHeight || 0;
}else {
return uni.getSystemInfoSync().windowHeight;
}
}
//微信小程序只能在页面内调用,不能导入调用,导入调用无效
export function getElementToTopHight( element : string ) : number {
//初始高度
let initHight = 0;
uni.createSelectorQuery().select( element ).boundingClientRect( ( res : any ) => {
initHight = res.top;
}).exec();
return initHight;
}
//获取页面剩余高度
import { getCurrentInstance } from "vue";
export async function getPageResidueDIST(nodeKey: string) : Promise<number> {
const query = uni.createSelectorQuery().in(getCurrentInstance());
let systemInfo = await uni.getSystemInfo();
let nodeToTop : number = await new Promise((ok, _) => {
query
.select(nodeKey)
.boundingClientRect((data: any) => {
ok(data.top);
})
.exec();
});
return systemInfo.windowHeight - nodeToTop;
}
运行效果图: