uniapp 如何获取页面高度
在uniapp开发中,如何动态获取当前页面的高度?我需要获取页面高度来调整某些元素的布局,但试过window.innerHeight和document.documentElement.clientHeight都无法正常获取。请问正确的实现方式是什么?需要兼容H5和小程序平台。
2 回复
在uni-app中获取页面高度,可以使用uni.getSystemInfoSync()获取屏幕高度,或使用uni.createSelectorQuery()获取具体元素高度。
在 UniApp 中获取页面高度,通常使用 uni.getSystemInfoSync() 方法获取屏幕高度,或结合页面生命周期计算实际内容高度。以下是具体方法:
1. 获取屏幕高度(窗口高度)
使用 uni.getSystemInfoSync() 同步获取系统信息,从中提取 windowHeight(窗口高度)。
onLoad() {
const systemInfo = uni.getSystemInfoSync();
const windowHeight = systemInfo.windowHeight; // 页面窗口高度
console.log('页面窗口高度:', windowHeight);
}
2. 获取整个页面内容高度
如果页面内容超出屏幕,可通过 uni.createSelectorQuery() 查询页面根节点高度。
onReady() {
const query = uni.createSelectorQuery().in(this);
query.select('#app').boundingClientRect(data => {
const pageHeight = data.height; // 整个页面内容高度
console.log('页面内容高度:', pageHeight);
}).exec();
}
注意:在 onReady 生命周期中调用,确保节点已渲染。#app 是页面根元素选择器,可根据实际情况调整。
3. 注意事项
- 平台差异:
windowHeight在不同平台可能包含导航栏,内容高度需根据实际结构计算。 - 组件使用:在自定义组件中使用时,需加
.in(this)指定作用域。
示例代码
export default {
data() {
return {
windowHeight: 0,
contentHeight: 0
};
},
onLoad() {
// 获取窗口高度
const systemInfo = uni.getSystemInfoSync();
this.windowHeight = systemInfo.windowHeight;
},
onReady() {
// 获取页面内容高度
const query = uni.createSelectorQuery().in(this);
query.select('.page-container').boundingClientRect(data => {
this.contentHeight = data.height;
}).exec();
}
};
根据需求选择合适的方法:窗口高度用 getSystemInfoSync,内容高度用 createSelectorQuery。

