原声微信小程序自定义顶部导航栏 . 自定义navigationBar。 (单页面设置)

本文实例为大家分享了微信小程序自定义导航栏的具体代码,供大家参考,具体内容如下


实现自定义大致需要以下?步骤:

1.在页面.JSON文件进行相关配置,以便去掉原生

"navigationStyle":"custom"

备注: navigationStyle(导航栏样式),参数: default = 默认样式,custom = 自定义样式。 

2.在页面.js文件onLoad生命周期函数中分别调用微信的getSystemInfoAsync() 与 getMenuButtonBoundingClientRect()方法

 // 1.获取胶囊按钮的布局位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
 // 2.获取设备系统信息
    const systemInfo = wx. getSystemInfoAsync();

备注:  wx.getSystemInfoAsync用于获取设备信息, wx.getMenuButtonBoundingClientRect用于获取获取胶囊按钮的布局位置信息

3.根据上一步调返回数据再按照官方文档调用相关参数

let a = systemInfo.statusBarHeight + 44;// 导航栏高度
let b = systemInfo.screenWidth - menuButtonInfo.right;// 胶囊距右方间距(方保持左、右间距一致)
let c = menuButtonInfo.top - systemInfo.statusBarHeight;// 胶囊距底部间距(保持底部间距一致)
let d = menuButtonInfo.height;// 胶囊高度(自定义内容可与胶囊高度保证一致)

4.最后在页面使用即可 看样式


5.完整代码: ()

index.json 文件 :

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

index.js 文件定义 :

 data: {
    navBarHeight: 0, //导航栏高度
    titleBottom: 0, //顶部距离
    title:'自定义顶部'
    // -----
  },

  /**
   * 事件处理
   */
  getHeights() {
    let that = this
    // 1.获取胶囊按钮的布局位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    // 2.获取设备信息
    const systemInfo = wx.getSystemInfoSync();
    // 3.计算:计算公式:导航栏高度 = 状态栏高度 + 44。
    // 导航栏高度 = 状态栏高度 + 44
    this.setData({
      navBarHeight: systemInfo.statusBarHeight + 44,
      titleBottom: systemInfo.statusBarHeight
    })
    console.log(systemInfo.statusBarHeight)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getHeights()
  },

index.wxml 文件顶部使用 :


<!-- 顶部 -->
<view class="contentsPages" style="height:{{navBarHeight}}px; padding: {{titleBottom+45}}rpx 0rpx 0rpx 20rpx;">
  <view class="title">
    {{title}}
  </view>
</view>
<!-- 主体 -->
<view class="content" style="height: calc(100% - {{navBarHeight}}px);">
  内容
</view>

index.wxss文件优化页面样式 : 

page {
  box-sizing: border-box;
  width: 100vw;
  height: 100vh;
} 

.contentsPages {
  box-sizing: border-box;
  background-color:#f7f7f7;
}

.title{
  font-size: 30rpx;
}

.content{
  width: 100vw;
  box-sizing: border-box;
  background-color: #ffffff;
}

谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值