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

本文详细介绍了如何在微信小程序中自定义导航栏,并显示未读消息的数量。首先在App.js中计算状态栏和导航栏的高度并存储到缓存,然后在message.json中配置使用自定义导航栏。接着在message.wxml中编写自定义导航栏的结构,包括返回按钮和消息数量的显示。最后在message.js中处理返回按钮的点击事件。通过这种方式,实现了在导航栏中动态展示未读消息的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、参考文章

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
        })
    },

   
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值