最近菜鸟做微信小程序,然后有一个图片置顶的功能
这个功能就需要把微信自带的导航栏样式给去掉,使用自定义导航栏样式,但是这个又产生一个问题,导航栏标题文字就不是很好适配了,因为不同手机型号,距离最上面的距离是不同的!
去掉导航栏的代码:
app.json
"window": {
"navigationStyle": "custom"
},
2023/6/1 补充(2024/1/4 改)
菜鸟突然发现,之前写的已经成为历史了,现在微信小程序可以通过 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>XXXXlims系统</text>
</view>
</view>
界面.wxss
page {
height: 100vh;
overflow: hidden;
}
.navtitleBox {
background-color: #3f8cff;
height: 100%;
}
.title {
text-align: center;
transform: translateY(-50%);
color: #fff;
}
注意
不能作用于 text 标签,不然无效
效果:
过时
这里菜鸟的解决办法是借鉴导师给我的代码,这里记录:
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>
2023/5/30 补充:
如果有的界面又要使用到默认的样式,那就在 界面.json 文件中写入下面代码,其他的导航栏设置才能生效!
"navigationStyle": "default"