微信小程序-自定义导航栏及返回上一级页面的实现

一、参考文章

1、微信小程序自定义navigationBar
2、微信小程序返回上一级页面的实现代码
3、小程序开发——常用布局

二、需求

在导航栏中需要显示信息的“未读数量”,所以需要自定义导航栏

三、 最终效果

在这里插入图片描述

四、实现

1、App.js:计算各种所需高度(参考文章1),放入缓存,供页面使用

  onLaunch: function(options) {
    
    
      //获取自定义导航栏高度-用于信息页面--tcy
      this.getNavigationBarHeight();
  },

  //获取自定义导航栏高度-用于信息页面--tcy
  getNavigationBarHeight(){
    
    
    const {
    
     statusBarHeight, platform } = wx.getSystemInfoSync()
    const {
    
     top, height } = wx.getMenuButtonBoundingClientRect()

    // 状态栏高度
    wx.setStorageSync('statusBarHeight', statusBarHeight)
    // 胶囊按钮高度 一般是32 如果获取不到就使用32
    wx.setStorageSync('menuButtonHeight', height ? height : 32)
    
    // 判断胶囊按钮信息是否成功获取
    if (top && top !== 0 && height && height !== 0) {
    
    
        const navigationBarHeight = (top - statusBarHeight) * 2 + height
        // 导航栏高度
        wx.setStorageSync('navigationBarHeight', navigationBarHeight)
    } else {
    
    
        wx.setStorageSync(
          'navigationBarHeight',
          platform === 'android' ? 48 : 40
        )
    }
  },

2、message.json:需自定义导航栏页面的json文件

{
    
    
  "usingComponents": {
    
    },
  "navigationBarBackgroundColor": "#ffffff",
  "navigationBarTextStyle": "black",
  //自定义导航栏所需的设置
  "navigationStyle": "custom"
}

3、message.wxml

<!-- 自定义导航栏 -->
<view style="height: {
    
    {navigationBarAndStatusBarHeight}}px;background-color:#fff;width: 100%;display: flex;flex-direction: row;">
    <view style="padding-top:{
    
    {statusBarHeight+10}}px;width: 100%;">
        <image src="/pages/images/back.png" style="height: 20px; width: 20px;padding-left:3vw;float: left;" bindtap="back"></image>
        <view style="float: left;margin-left: 140px;font-size: 13px;"> 
            <text>消息{
    
    {
    
    wdsl > 0 ? '('+wdsl+')' : ''}}</text>
        </view>
    </view>
</view>

4、message.wxss

5、message.js

Page({
    
    

    /**
     * 页面的初始数据
     */
    data: {
    
    
        //获取各种高度信息---tcy
        // 状态栏高度
        statusBarHeight: wx.getStorageSync('statusBarHeight'),
        // 导航栏高度
        navigationBarHeight: wx.getStorageSync('navigationBarHeight'),
        // 胶囊按钮高度
        menuButtonHeight: wx.getStorageSync('menuButtonHeight'),
        // 导航栏和状态栏高度
        navigationBarAndStatusBarHeight:
            wx.getStorageSync('statusBarHeight') +
            wx.getStorageSync('navigationBarHeight'),
    },

    //返回按钮实现
    back(){
    
    
        //返回上一级,关闭当前页面
        wx.navigateBack({
    
    
        	delta: 1
        })
    },

   
})

猜你喜欢

转载自blog.csdn.net/qq_42622871/article/details/124141262