微信小程序自定义导航栏

目录

1.开始

2.图解

3.实现


1.开始

在 页面json文件中把 "navigationStyle" 设置为 "custom"就可以自定义导航栏了

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

2.图解

3.实现

微信AIP wx.getMenuButtonBoundingClientRect() 可以得到胶囊信息
Object wx.getMenuButtonBoundingClientRect() | 微信开放文档 (qq.com)

在这里需要用到{ width, height, top, right }

再根据微信AIP wx.getSystemInfo() 获取设备信息,得到状态栏高度

wx.getSystemInfo(Object object) | 微信开放文档 (qq.com)

 通过状态栏高度和胶囊信息,可以得到胶囊距状态栏距离,内容的宽高等

接下来就是实现了

.wxml

<view class="nav" style="height: {{navHeight}}px; width: 100%; background: rgba(255, 255, 255, {{opacity}});">
    <view class="navcontent" style="margin-top: {{marginTop}}px; width: {{contentWidth}}px;height: {{contentHeight}}px;">
//这里的返回按钮用的是vant的icon
      <van-icon name="arrow-left" size="22" style="margin-left: {{marginRight}}px;" bind:click="onClickBack" />
      <view class="navtitle" style="margin-left: {{titleMargin}}px;">标题</view>
    </view>
 </view>

.js

data: {
    navHeight:'',//导航栏高,
    menuButtonInfo:'',//胶囊信息
    marginTop: '', // 上边距
    marginRight:'',//右侧边距
    contentHeight:'',//内容高度
    contentWidth:'',//内容宽度
    titleMargin:'',//标题距右侧距离
  },
onLoad(options) {
    this.getSystemInfo()
  },
getSystemInfo(){
    this.setData({
      menuButtonInfo: wx.getMenuButtonBoundingClientRect()
    })
    const { top, width, height, right } = this.data.menuButtonInfo
    wx.getSystemInfo({
      success: (res) => {
        const { statusBarHeight } = res //状态栏高度
        const margin = top - statusBarHeight//胶囊距状态栏距离
        this.setData({
          navHeight: (height + statusBarHeight + (margin * 2)),
          marginTop: statusBarHeight + margin, // 状态栏 + 胶囊按钮边距
          contentHeight: height,  // 与胶囊按钮同高
          contentWidth: right - width, // 胶囊按钮右边坐标 - 胶囊按钮宽度 = 按钮左边可使用宽度
          marginRight:margin,
          titleMargin:(right+margin)/2-60
        })
      },
    })
  },
// 点击返回
  onClickBack() {
    wx.navigateBack({
      delta: 1
    })
  },

.wxss

.nav {
  padding: 0rpx;
  position: fixed;
  top: 0;
  z-index: 900;
}

.navcontent {
  display: flex;
  align-items: center;
}

.navtitle {
  width: 60px;
  text-align: center;
  font-size:28rpx;
  font-weight: 500;
}

参考链接

https://blog.csdn.net/a1369508468/article/details/105844093

https://www.cnblogs.com/sese/p/9761713.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值