菜鸟突然发现,之前写的已经成为历史了,现在微信小程序可以通过 api 直接获取到这些高度,所以菜鸟在这里进行更新!
app.js的onLaunch加入下方代码:
// 获取胶囊的详细信息
let menuButtonObject = wx.getMenuButtonBoundingClientRect();
wx.getSystemInfo({
success: res => {
// 导航高度
let statusBarHeight = res.statusBarHeight,
// 胶囊距离顶部高度
navTop = menuButtonObject.top,
// 胶囊按钮与右侧的距离 = windowWidth - right + 胶囊宽度(包括右边距离)
navObjWid = res.windowWidth - menuButtonObject.right + menuButtonObject.width,
// 导航栏整体高度
navHeight = statusBarHeight + menuButtonObject.height + (navTop - statusBarHeight) * 2;
this.globalData.navHeight = navHeight;
this.globalData.navTop = navTop;
this.globalData.navObj = menuButtonObject.height; // 胶囊高度
this.globalData.navObjWid = navObjWid;
// 设置title的距离(这个只是文字顶部到了位置,还要将title向上移动自己50%高度)
this.globalData.headerHeight = navTop + menuButtonObject.height/2;
},
fail(err) {
console.log(err);
}
})
1、上述 menuButtonObject.top - statusBarHeight 就是绿色框的高度
2、上述获取到的都是 px 不是 rpx
具体参考:
微信小程序实现自定义头部导航栏(详细)
界面.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
headerHeight: app.globalData.headerHeight,
},
})
界面.wxml
<view
class="navtitleBox"
style="padding-top:{{headerHeight}}px"
>
<view class="title">
<text>ppptext>
view>
view>
界面.wxss
.title {
transform: translateY(-50%);
}
不能作用于 text 标签,不然无效
这里菜鸟的解决办法是借鉴导师给我的代码,这里记录:
app.json
"window": {
"navigationStyle": "custom"
},
app.js
// 获取标题位置
const { model, system, statusBarHeight } = wx.getSystemInfoSync();
var headHeight;
if (/iphone\s{0,}x/i.test(model)) {
headHeight = 88;
} else if (/iphone\s{0,}1/i.test(model)) { // 适配iPhoneX以上的
headHeight = 88;
} else if (system.indexOf('Android') !== -1) {
headHeight = 68;
} else {
headHeight = 64;
}
this.globalData.headerHeight = headHeight;
this.globalData.statusBarHeight = statusBarHeight;
界面.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
headerHeight: app.globalData.headerHeight,
statusBarHeight: app.globalData.statusBarHeight,
},
})
界面.wxml
<view
class="navtitleBox"
style="padding-top:{{(headerHeight + statusBarHeight)/2 - 12}}px"
>
<text class="navtitle">智慧用电text>
view>
如果有的界面又要使用到默认的样式,那就在 界面.json 文件中写入下面代码,其他的导航栏设置才能生效!
"navigationStyle": "default"