前言:在开发小程序的过程中,很经常会遇到各种各样的需求,有些顶部没法很单一的只显示标题和纯色的背景,因此就需要按照项目需求自定义。
思路:先根据设计稿在页面中绘制出结构和样式的内容,接着固定的样式值改成动态的,最后一步把写好的内容搬到组件上去。这里需要的动态值有状态栏的高度和胶囊位置的文本栏高度,都可以通过api获取到。
1.在app.vue页面中统一获取到动态值
globalData: {
statusBarHeight: '', //状态栏高度
navHeight:'', //文本内容高度
},
onLaunch: function() {
let that = this;
let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
uni.getSystemInfo({
success(res) {
let statusBarHeight = res.statusBarHeight;
let navHeight = menuButtonInfo.height + (menuButtonInfo.top - statusBarHeight) *2;
//胶囊在页面中的位置-状态栏高度得到的间距*2 再加上胶囊的高度
that.globalData.statusBarHeight = statusBarHeight;
that.globalData.navHeight = navHeight;
}
})
},
附胶囊按钮api:getMenuButtonBoundingClientRect() | uni-app官网
系统信息api:getMenuButtonBoundingClientRect() | uni-app官网
2.创建一个组件页面把结构放上去就行:
(如果需要判断页面是否有返回箭头的话就从页面中传入barData对象来判断,目前我这个项目暂不需要所以写的比较简单)
<template>
<view class="custombar" :style="{height:(statusBarHeight+navHeight)+'px'}">
<view class="status_bar" :style="{height:statusBarHeight+'px'}"></view>
<view class="nav_bar" :style="{height:navHeight+'px'}">
<image v-if="barData.hasReturn" class="return" src="/static/image/return.png"></image>
<view class="title">
<image src="/static/logo.png"></image>
<text>uniapp</text>
</view>
</view>
</view>
</template>
<script>
const app = getApp();
export default {
props:['barData'],
data() {
return {
statusBarHeight:app.globalData.statusBarHeight,
navHeight:app.globalData.navHeight,
}
},
}
</script>
<style scoped lang="less">
.custombar{position: fixed;top: 0rpx;left: 0;width: 100%;z-index: 999;text-align: center;height: 45px;background-color: #002FA7;
.nav_bar{position: relative;z-index: 999;
.return{position: absolute;transform: translateY(-50%);width: 40rpx;height: 40rpx;top: 50%;left: 30rpx;z-index: 99;}
.title{position: relative;transform: translate(-50%, -50%);left: 50%;top: 50%;font-size: 0;
image,text{display: inline-block;vertical-align: middle;}
image{width: 72rpx;height: 72rpx;margin-right: 14rpx;}
text{font-size: 34rpx;color: #fff;font-weight: bold;letter-spacing: 6rpx;}
}
}
}
</style>
3.页面效果展示如下: