前言
-
在实际开发中我们是根据需求,原型图,功能配色来开发,并不是考虑这个组件是不是能实现
-
首页我们不需要跳转时,会出现标题左移,渐变色,输入框,等等布局,原生导航栏就不满足需求
-
这时我们需要自定义导航栏,uni-app 确实提供了css变量,告诉我们手机系统栏高度,胶囊按钮高度,但我们写死时会因为不同的机型,导致页面的布局破坏,这是因为不同手机分辨率,缩放有差异,会导致系统栏,胶囊按钮差异,这是如果我们高度全局写死就会乱。
-
换个角度思考,那为什么微信自己封装的代码,就可以适配这些问题-是因为它把高度写活了。我们只需要调用api,在首次进入页面时候。获取手机系统栏,胶囊按钮,就可以解决这些问题。
代码实现-可以直接复制
<template>
<view class="content">
<!-- 背景导航栏 -->
<view class="background-plate" :style="{ height:titleheight + titletop + 10 + 'px'}">
</view>
<!-- 标题 -->
<view class="status_bar" :style="{ height:titleheight + 'px',top: titletop + 'px'}">
<text>自定义导航栏</text>
</view>
<!-- 内容 -->
<view class="content-statistics" :style="{ paddingTop:titleheight + titletop + 10 + 'px'}">
</view>
</view>
</template>
<script>
export default {
data() {
return {
// 胶囊按钮高度
titleheight: 0,
// 胶囊到顶部距离
titletop: 0,
}
},
onLoad() {
// 或许胶囊按钮各种参数
this.getHeight()
},
methods: {
getHeight() {
let res = uni.getMenuButtonBoundingClientRect();
this.titletop = res.top;
this.titleheight = res.height
console.log(res);
console.log("titletop的值", this.titletop);
console.log("titleheight的值", this.titleheight);
console.log("一半的titleheight的值", this.titleheight / 2);
},
}
}
</script>
<style lang="scss">
.content {
.background-plate {
width: 100vw;
background: skyblue;
position: fixed;
left: 0;
z-index: 5;
}
.status_bar {
width: 100vw;
position: fixed;
left: 0;
line-height: 64rpx;
padding-left: 32rpx;
z-index: 10;
text {
font-size: 36rpx;
font-family: PingFang SC-Heavy, PingFang SC;
font-weight: 800;
color: #FFFFFF;
}
}
}
</style>
总结:
经过这一趟流程下来相信你也对 uni-app 自定义导航栏-解决适配问题 有了初步的深刻印象,但在实际开发中我 们遇到的情况肯定是不一样的,所以我们要理解它的原理,万变不离其宗。加油,打工人!
什么不足的地方请大家指出谢谢 -- 風过无痕