微信小程序自定义导航栏及设置背景

901 阅读1分钟

先看效果

image.png

分析过程及遇到的问题

  • 整个页面背景是一个背景图
  • 导航栏要透明,显示出背景图
  • 页面内容滚动至导航栏位置时,因导航栏透明,无法隐藏问题

解决第一个问题:给页面设置背景

.container {
  font-size: 28rpx;
  color: #454545;
  background-image: url('xxx'); /* 替换为你的图片路径 */
  background-size: cover /* 使背景图片覆盖整个元素 */
  background-repeat: no-repeat;
  background-attachment: fixed;
  overflow: hidden;
  height: 100vh;
}
  • 根元素class 为container
  • 背景图因微信限制不能是本地图片,可以丢到服务器上填url

解决第二个问题:自定义导航栏

开启全局导入

//app.json
...
"usingComponents": {
    "nav-bar": "/component/nav-bar/index"
},
...

//app.js 因各手机状态栏高度不同  动态获取下
...
onLaunch: function () {
     wx.getSystemInfo({
          success: res => {
            //导航高度
            let custom = wx.getMenuButtonBoundingClientRect()
            this.globalData.statusBarHeight = res.statusBarHeight
            this.globalData.navBarHeight = custom.height + (custom.top - res.statusBarHeight) * 2
          }, fail(err) {
            console.log(err);
          }
    })
},
//设置下全局变量 页面中使用
globalData: {
    statusBarHeight: 0,
    navBarHeight: 0
},
...

页面中使用

//js文件
data: {
    navheight: app.globalData.statusBarHeight + app.globalData.navBarHeight+10,
    nvabarData:{
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '修改密码', //导航栏 中间的标题
    }
}
//wxml文件 navheight怎么使用请看下边
<nav-bar navbar-data='{{nvabarData}}'></nav-bar>

其实就是创建一个组件,然后全局引入。 查看代码请 跳转到仓库

解决第三个问题:页面内容滚动至导航栏位置时,因导航栏透明,无法隐藏问题

中心思想就是使用局部滚动也就是scroll-view组件,代码如下

//wxml
<view class="container">
  <nav-bar navbar-data='{{nvabarData}}'></nav-bar>
    <scroll-view scroll-y="true" style="margin-top: {{navheight}}px;height: calc(100vh - {{navheight}}px);">
        //你的布局代码
    </scroll-view>
</view>

至此效果已全部实现。