小程序自定义导航栏组件

这篇文章展示了如何在微信小程序中创建自定义导航栏,包括处理状态栏高度、胶囊按钮的位置以及绑定事件来实现返回功能。在WXML中定义了导航栏视图结构,而在App.js中获取设备信息以动态计算导航栏的高度并设置全局变量。
摘要由CSDN通过智能技术生成

小程序代码片段
**

效果图

**
在这里插入图片描述

代码片段(点击可直接查看功能实现的全部代码)

小程序代码片段

部分代码

wxml

<view class="navBar {{navbarData.position?'navBarPosition':''}}" style="height: {{navbarHeight}}px;">
  <view class="navImg" style='margin-top: {{statusBarHeight}}px;top: 18rpx' >
    <image src="/assets/images/back.png" bindtap="_goBack" wx:if="{{imgStatus}}" class="img"></image>
    <image src="/assets/images/back2.png" bindtap="_goBack" style="width: 40rpx; height: 40rpx;" wx:else=""></image>
  </view>
  <view  style='line-height:{{navbarBtn.height + navbarBtn.top}}px;margin-top: {{statusBarHeight}}px; top: 8rpx' class="{{imgStatus ? 'navText' : 'textColor'}}" >
    <text class="textTitle">{{navbarData.title }}</text>
  </view>
</view>

app.js

App({
  onLaunch() {
    wx.getSystemInfo({ // 获取设备信息
      success: (res) => {
        this.globalData.systeminfo = res
        //导航栏
        let statusBarHeight = res.statusBarHeight // 状态栏高度
        let headerPosi = wx.getMenuButtonBoundingClientRect() // 胶囊位置信息
        let btnPosi = { // 胶囊实际位置,坐标信息不是左上角原点
          height: headerPosi.height,
          width: headerPosi.width,
          // 胶囊top - 状态栏高度
          top: headerPosi.top - statusBarHeight,
          // 胶囊bottom - 胶囊height - 状态栏height (现胶囊bottom 为距离导航栏底部的长度)
          bottom: headerPosi.bottom - headerPosi.height - statusBarHeight,
          // 屏幕宽度 - 胶囊right
          right: res.screenWidth - headerPosi.right
        }

        // 原胶囊bottom + 现胶囊bottom
        this.globalData.navbarHeight = headerPosi.bottom + btnPosi.bottom
        this.globalData.statusBarHeight = statusBarHeight
        this.globalData.navbarBtn = btnPosi
        wx.setStorageSync('navbarHeight', this.globalData.navbarHeight)

      },
    })
    // 获得胶囊按钮位置信息
    this.globalData.headerBtnPosi = wx.getMenuButtonBoundingClientRect()

  },
  globalData: {
    userInfo: null,
    headerBtnPosi: {}, // 胶囊按钮位置信息
    navbarHeight: 0,
    statusBarHeight: 0,
    navbarBtn: 0
  }
})

app.json

{
  "pages": [
    "index/index"
  ],
  "window": {
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "Weixin",
    "navigationBarTextStyle": "black",
    "navigationStyle":"custom" 
  },
  "style": "v2",
  "sitemapLocation": "sitemap.json",
  "lazyCodeLoading": "requiredComponents"
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

湾流~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值