有一个需求是:要自定义微信小程序自定义顶部导航栏
在 page.json 文件里面,pages 配置数组当中找到想要自定义导航栏的页面,添加上"navigationStyle": "custom",这样子之后就只会保留右上角胶囊按钮了。
{
"pages": [
{
"path": "pages/components/HomePage/index",
"style": {
"navigationBarTitleText": "主页"
"navigationStyle": "custom"
}
},
],
}
因为在不同的手机型号头部那条栏目高度可能不一致,所以为了我们适配更多型号,我们需要计算3个值:
1. 整个导航栏的高度:
2. 胶囊按钮与顶部的距离;
3. 胶囊按钮与右侧的距离。
这里我们需要通过方法来获取小程序右上角胶囊信息与设备信息并计算出对应值
let custom = uni.getMenuButtonBoundingClientRect(); // 小程序右上角胶囊信息
let system = uni.getSystemInfoSync(); // 获取设备信息
this.navHeight = system.statusBarHeight + 44; // 导航栏的高度
this.customTop = custom.top; // 胶囊按钮与顶部的距离
this.customHeight = custom.height; // 胶囊按钮与右侧的距离
将对应的值动态设置到对应标签上
加入
根据设计稿,再进行一些微调
.navbar {
width: 100%;
display: flex;
align-items: center;
.topInfo {
width: 100%;
display: flex;
align-items: center;
padding-bottom: 8px;
padding-left: 10px;
.searchCoceral {
flex: 1;
margin-left: 10px;
::v-deep .u-search {
width: 170px;
height: 20px;
}
}
}
}
参考文章: