自定义微信小程序导航栏NavigationBar

该文章介绍了如何在微信小程序中自定义NavigationBar,通过获取系统信息和菜单按钮的布局,计算出导航栏的高度、胶囊按钮的尺寸等,设置全局变量并在页面中使用这些数据来定制导航栏的样式和位置,实现防伪溯源的展示效果。
摘要由CSDN通过智能技术生成

自定义微信小程序NavigationBar

App.js

// app.js
App({
  onLaunch() {
     // 自定义头部
     let menuButtonObject = wx.getMenuButtonBoundingClientRect();
     wx.getSystemInfo({
       success: res => {
         // 导航高度
         let statusBarHeight = res.statusBarHeight,
           navTop = menuButtonObject.top,
           // 胶囊按钮与右侧的距离=windowWidth-right+胶囊宽度
           navObjWid = res.windowWidth - menuButtonObject.right + menuButtonObject.width,
           navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;
         this.globalData.navHeight = navHeight;//导航栏总体高度
         this.globalData.navTop = navTop;//胶囊距离顶部距离
         this.globalData.navObj = menuButtonObject.height;//胶囊高度
         this.globalData.navObjWid = navObjWid;//胶囊宽度(包括右边距离)
         this.globalData.windowWidth = res.windowWidth;
         this.globalData.windowHeight = res.windowHeight;
       },
       fail(err) {
         console.log(err)
       }
     })

  },
  globalData: {
    navHeight: 0,
    navTop: 0,
    navObj: 0,
    navObjWid: 0,
    windowWidth: 0,
    windowHeight:0,
  }
})

page.js文件

var app =  getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 导航栏高度
    navHeight: app.globalData.navHeight,
    // 导航栏距离顶部距离
    navTop: app.globalData.navTop,
    // 胶囊的高度
    navObj: app.globalData.navObj,
    // 胶囊宽度+距右距离
    navObjWid: app.globalData.navObjWid ,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.setNavigationBarColor({
      frontColor:"#ffffff",
      backgroundColor:"#ffffff"
    })
  },
}

page.json文件

{
  "usingComponents": {},
  "navigationStyle": "custom",
}

page.wxml文件

<view class="header">
      <image src="https://w.wallhaven.cc/full/9d/wallhaven-9doq78.png" mode="aspectFill" class="header-bg" />
      <view style="height: {{navHeight*2}}rpx; ">
        <view style="height: {{navObj*2}}rpx; padding-top: {{navTop*2}}rpx; position: relative; width: 100%; text-align: center; line-height: {{navObj*2}}rpx; color: #ffffff; font-size: 28rpx;"  >
              防伪溯源 
        </view>
      </view>
</view>

page.wxss文件

page {
    width: 100%;
}
.header {
    width: 100%;
    position: relative;
    height: 2000rpx;
}
.header .header-bg{
  height: 100%;
  width: 100%; 
  position: absolute;
  left: 0;
  top: 0;
}

效果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值