注:以下举例代码为uni-app
显示如下效果
一、需要实现的功能
- 顶部自定义导航条
- 导航的背景图与页面功能的背景图衔接
二、实现思路
- 计算不同机型顶部导航条的高度,单位px
- 标题栏高度 = (胶囊按钮的top值 - 胶囊按钮高度)* 2(指上下间距 ) + 胶囊按钮高度
- 导航总高度 = 状态栏高度 + 标题栏高度
const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
uni.getSystemInfo({
success: res => {
const { statusBarHeight } = res
// 标题栏高度
const navHeight = (menuButtonInfo.top - statusBarHeight) * 2 + menuButtonInfo.height
// 顶部自定义导航总高度
const totalNavHeight = statusHeight + navHeight
...
}
})
- 导航背景图与页面功能背景图无缝衔接
三、实现过程
- 顶部导航
<view :style="{ height: totalNavHeight + 'px' }">
<view class="nav-bar__fixed" :style="{ height: totalNavHeight + 'px' }">
<image class="nav-bar__bg-img" src="背景图片路径.svg"></image>
<view class="title-wrap">
<view class="nav-bar__status" :style="{ height: statusBarHeight + 'px' }"></view>
<view class="nav-bar__info" :style="{ height: navHeight + 'px' }">
自定义导航的内容...
</view>
</view>
</view>
</view>
<style>
.nav-bar__fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
overflow: hidden; // 溢出导航栏高度的其他内容(即图片)隐藏
...
}
</style>
- 与背景图衔接的部分:
<view class="home-top">
<view class="hack-nav-placeholder" :style="{ height: totalNavHeight + 'px' }"></view>
<image class="home-top__bg-img" src="背景图片路径.svg"></image>
<view class="home-top_wrap" :style="{ height: areaHeight + 'px', top: totalNavHeight +'px' }">
中间区域内容...
</view>
</view>
<script>
const transferBgImgHeightToPX = unitTransform(610, 'px') // 背景图片的高度转换成px,610是2倍切图中图片的高度
const areaHeight = transferBgImgHeightToPX - totalNavHeight
/**
* 单位转换px转rpx
*/
type transferType = 'px' | 'rpx'
function unitTransform(pixel: number, type: transferType) {
switch (type) {
case 'rpx':
return (pixel * 750) / uni.getSystemInfoSync().windowWidth
break
case 'px':
return (pixel / 750) * wx.getSystemInfoSync().windowWidth
break
}
}
</script>
<style>
.hack-nav-placeholder {
background-color: #fff; // 设置成与页面背景色相同的颜色
}
</style>
四、最终效果就实现如开头所示的效果
【注意:window环境下运行使用,需做单独处理,可根据uni.getSystemInfo()返回数据中的platform可得知当前运行平台】