微信小程序开发之: 获取系统状态栏 & 胶囊高度(兼容 Iphone6)
开篇
获取系统状态栏、右上角胶囊高度,属于小程序开发中高频使用的功能。在此分享一段实现代码,实测在 Iphone6 等机型上也能获取到正确的高度信息。
获取高度
1// 状态栏 & 胶囊高度
2try {
3 const res = wx.getSystemInfoSync();
4 const custom = wx.getMenuButtonBoundingClientRect();
5 // 状态栏高度
6 this.globalData.statusBarHeight = res.statusBarHeight;
7 // 胶囊高度
8 this.globalData.customBarHeight = (custom.top - res.statusBarHeight) * 2 + custom.height;
9} catch (e) {
10 console.error(e);
11}
应用实例
index.xml:
1<!-- 状态栏 -->
2<view style="height: {{ statusBarHeight }}px; background-color: red;"></view>
3<!-- 胶囊 -->
4<view style="height: {{ customBarHeight }}px; background-color: green;"></view>
index.ts:
1Page({
2 data: {
3 // 标题栏高度
4 statusBarHeight: app.globalData.statusBarHeight,
5 customBarHeight: app.globalData.customBarHeight,
6 }
7});
参考资料
M_SSY: 微信小程序获取顶部状态栏和胶囊的高度