有一个需求是:要自定义微信小程序自定义顶部导航栏
第一步:将对应页面的"navigationStyle" 设置为 "custom"
在 page.json 文件里面,pages 配置数组当中找到想要自定义导航栏的页面,添加上"navigationStyle": "custom",这样子之后就只会保留右上角胶囊按钮了。
{
"pages": [
{
"path": "pages/components/HomePage/index",
"style": {
"navigationBarTitleText": "主页"
"navigationStyle": "custom"
}
},
],
}
第二步:计算相关值
因为在不同的手机型号头部那条栏目高度可能不一致,所以为了我们适配更多型号,我们需要计算3个值:
- 整个导航栏的高度:
- 胶囊按钮与顶部的距离;
- 胶囊按钮与右侧的距离。
这里我们需要通过方法来获取小程序右上角胶囊信息与设备信息并计算出对应值
let custom = uni.getMenuButtonBoundingClientRect(); // 小程序右上角胶囊信息
let system = uni.getSystemInfoSync(); // 获取设备信息
this.navHeight = system.statusBarHeight + 44; // 导航栏的高度
this.customTop = custom.top; // 胶囊按钮与顶部的距离
this.customHeight = custom.height; // 胶囊按钮与右侧的距离
第三步:应用到结构上
将对应的值动态设置到对应标签上
<view class="navbar" :style="{ height: navHeight + 'px' }">
<view
class="topInfo"
:style="{
marginTop: customTop + 'px',
height: customHeight + 'px',
paddingRight: customRight + 'px',
}"
>
<view class="joinCocelal" style="width: 80px">
<text style="margin-right: 2px" @click="joinCoceral">加入</text>
<u-icon name="arrow-right" style="font-size: 14px"></u-icon>
</view>
<view class="searchCoceral">
<u-search
placeholder="查找"
v-model="findCoceralVal"
:show-action="false"
:style="{ height: customHeight + 'px' }"
></u-search>
</view>
</view>
</view>
根据设计稿,再进行一些微调
.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;
}
}
}
}
最终效果:
参考文章: