uni-app api 获取系统信息(高、宽)用法及封装
uni-app提供了异步(uni.getSystemInfo)和同步(uni.getSystemInfoSync)的2个API获取系统信息
uni.getSystemInfo
异步获取系统信息
success返回其他的参数(详细所有内容看官网)
注意:
-
屏幕高度 = 原生NavigationBar高度(含状态栏高度)+ 可使用窗口高度 + 原生TabBar高度 windowHeight不包含NavigationBar和TabBar的高度 Web端,windowTop等于NavigationBar高度,windowBottom等于TabBar高度 App端,windowTop等于透明状态NavigationBar高度,windowBottom等于透明状态TabBar高度 高度相关信息,要放在 onReady 里获取。太早取不到。高度宽度的单位都是px
uni.getSystemInfo({ success: function(res) { // *****高度宽度的单位都是px console.log(res.screenHeight); // 屏幕高度,包含导航栏 console.log(res.windowHeight); // 能够使用的窗口高度,不包含导航栏 console.log(res.screenWidth); // 屏幕宽度 console.log(res.windowWidth); // 能够使用的窗口宽度 console.log("windowHeight:",res.windowHeight) let windowHeight = res.windowHeight; } })
uni.getSystemInfoSync
获取系统信息的同步接口。调用参数和返回值同上getSystemInfo。
uni.getSystemInfoSync({ success: function(res) { // *****高度宽度的单位都是px console.log(res.screenHeight); // 屏幕高度,包含导航栏 console.log(res.windowHeight); // 能够使用的窗口高度,不包含导航栏 console.log(res.screenWidth); // 屏幕宽度 console.log(res.windowWidth); // 能够使用的窗口宽度 console.log("windowHeight:",res.windowHeight) let windowHeight = res.windowHeight; } })
获取活动区域高度方法封装
/** * 获取活动区域高度 * @param { nodeName } 节点名字 * @param { nodeHeight } 节点高度 * @param { nodeMPHeight } 节点margin 和 padding 的高度 * */ function getHeight(nodeName, nodeHeight = 0,nodeMPHeight = 0) { let pageHeight = uni.getSystemInfoSync().windowHeight; // 获取当前页面的高度 console.log("pageHeight: ",pageHeight) // 获取结节高度方法 // #ifdef H5 const query = uni.createSelectorQuery(); // #endif // #ifdef APP const query = uni.createSelectorQuery().in(this) // #endif // 获取当前结节高度值 let nHeight = nodeHeight query .select(nodeName) .boundingClientRect(data => { console.log("data.height: ",data.height) nHeight = data.height }) .exec(); let nowHeight = pageHeight - nHeight - nodeMPHeight console.log("nowHeight",nowHeight) return nowHeight + px } 2. 调用 /** * 获取滚动高度--高度相关信息,要放在 onReady 里获取,太早取不到; * 单位都是px * 将rpx单位值转换成px * uni.upx2px(600) + px; * */ this.h = this.getHeight(#content-head, 0, uni.upx2px(20));