微信小程序自定义顶部导航栏

1.在components(没有就在根目录下创建一下)文件夹下创建navigation-bar组件

2.在navigation-bar.js下,动态设置导航栏的高度

// components/navigation-bar/navigation-bar.js
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    navTitle:{
      type:String,
      value:"标题"
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    navHeight: 0, //导航栏高度
    menuTop: 0, //胶囊距顶部间距
    menuHeight: 0 //胶囊高度
  },

  lifetimes: {
    attached: function () {
      //系统信息
      const systemInfo = wx.getSystemInfoSync();
      //胶囊位置
      const capsuleInfo = wx.getMenuButtonBoundingClientRect();
      //计算导航栏高度
      let navHeight = systemInfo.statusBarHeight + capsuleInfo.height + (capsuleInfo.top - systemInfo.statusBarHeight) * 2
      let menuTop = capsuleInfo.top
      let menuHeight = capsuleInfo.height
      this.setData({
        navHeight,
        menuTop,
        menuHeight
      })
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {

  }
})

3.编写导航栏样式,navigation-bar.wmxl,navigation-bar.wxss

<!--components/navigation-bar/navigation-bar.wxml-->
<view class="nav" style="height: {{navHeight}}px;line-height: {{lineHeight}}px;">
  <view class="title" style="padding-top:{{menuTop}}px;height: {{menuHeight}}px;min-height: {{menuHeight}}px;line-height: {{menuHeight}}px;">{{navTitle}} </view>
</view>
/* components/navigation-bar/navigation-bar.wxss */
.nav{
  background-color: #000000;
  width: 100%;
}

.title{
  width: 100%;
  text-align: center;
  color: #ffffff;
  font-size: 36rpx;
}

4.在app.json中,设置顶部导航自定义模式

{
 "window": {
    "navigationStyle": "custom"
  }
}

5.在全局组件设置中设置导航栏组件,或者在需要的page页设置

{
  "usingComponents": {
    "navigation-bar":"/components/navigation-bar/navigation-bar"
  }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值