uniapp如何获取页面高度
在uniapp中如何动态获取当前页面的高度?我现在需要在页面加载完成后获取整个页面的实际高度,包括滚动区域的内容高度。尝试过使用uni.getSystemInfoSync()只能获取屏幕高度,而不是页面内容高度。请问有没有方法可以准确获取页面整体高度?特别是当页面内容超过一屏需要滚动时,如何正确计算总高度?
2 回复
在uniapp中,获取页面高度可以使用uni.getSystemInfoSync()获取屏幕高度,或通过uni.createSelectorQuery()获取页面元素高度。例如:
uni.getSystemInfoSync().windowHeight
或
uni.createSelectorQuery().select('.page').boundingClientRect(res => {
console.log(res.height)
}).exec()
在 UniApp 中,获取页面高度可以通过以下方法实现:
方法一:使用 uni.getSystemInfoSync()
通过系统信息获取屏幕高度,适用于获取整个窗口的高度。
const systemInfo = uni.getSystemInfoSync();
const windowHeight = systemInfo.windowHeight; // 窗口高度(不包含底部导航栏)
const screenHeight = systemInfo.screenHeight; // 屏幕总高度
windowHeight:可用窗口高度(不包括底部导航栏)。screenHeight:设备整个屏幕的高度。
方法二:使用 uni.createSelectorQuery()
获取页面中特定元素的高度,适用于动态内容或组件高度。
// 在 onReady 或 mounted 生命周期中调用
uni.createSelectorQuery().select('#yourElementId').boundingClientRect(data => {
if (data) {
const elementHeight = data.height;
console.log('元素高度:', elementHeight);
}
}).exec();
- 说明:替换
#yourElementId为实际元素的选择器(如.class或#id)。
方法三:通过页面生命周期获取
在 onReady 生命周期中结合 uni.getSystemInfoSync() 确保页面渲染完成。
export default {
onReady() {
const systemInfo = uni.getSystemInfoSync();
console.log('页面可用高度:', systemInfo.windowHeight);
}
}
注意事项
- 页面渲染时机:在
onReady或mounted后获取高度,避免因渲染未完成导致数据不准确。 - 单位适配:UniApp 默认使用
px,可通过uni.upx2px()转换 rpx 单位。 - 动态内容:若内容高度变化(如异步加载),需在数据更新后重新调用方法。
根据需求选择合适的方法即可快速获取页面或元素高度!

