微信小程序自定义导航栏

193 阅读1分钟

app.js中

  let menuButtonObject = wx.getMenuButtonBoundingClientRect();        wx.getSystemInfo({            success: res => {                let statusBarHeight = res.statusBarHeight,                    navTop = menuButtonObject.top, //胶囊按钮与顶部的距离                    navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2; //导航高度                this.globalData.navHeight = navHeight;                this.globalData.navTop = navTop * 2;                this.globalData.windowHeight = res.windowHeight;            },            fail(err) {                console.log(err);            }        })

导航栏组件中

  • navwrap.wxml

    {{navbarData.title}}已屏蔽
  • navwrap.js

    const app = getApp() Component({ properties: { navbarData: { //navbarData 由父页面传递的数据,变量名字自命名 type: Object, value: {}, observer: function (newVal, oldVal) {} }, isLno:{ type:Boolean, value:false }, backNum:{//返回第几页 type:Number, value:1 } }, data: { height: '', //默认值 默认显示左上角 navbarData: { showCapsule: 1 } }, attached: function () { // 获取是否是通过分享进入的小程序 this.setData({ share: app.globalData.share }) // 定义导航栏的高度 方便对齐 this.setData({ height: app.globalData.navHeight, statusBarHeight:app.globalData.statusBarHeight }) }, methods: { // 返回上一页面 _navback() { wx.navigateBack({ delta:this.data.backNum }) }, //返回到首页 _backhome() { wx.switchTab({ url: '/pages/index/index', }) } }

    })

  • navwrap.wxss

    /* 顶部要固定定位 标题要居中 自定义按钮和标题要和右边微信原生的胶囊上下对齐 nav-title*/ .nav-wrap { position: fixed; width: 100%; top: 0; background: #fff; color: #000; z-index: 9999999; } /* 标题要居中 */ .nav-title { position: absolute; text-align: center; max-width: 400rpx; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; top: 0; left: 0; right: 0; bottom: 0; margin: auto; font-size: 32rpx; color: #2c2b2b; font-weight: 500; } .nav-title text{ background: #FFF4F2; opacity: 1; border-radius: 4rpx; font-size: 20rpx; font-family: Source Han Sans CN; font-weight: 400; color: #FF4A2E; opacity: 1; padding: 4rpx 10rpx; box-sizing: border-box; margin-left: 16rpx; }

    .nav-capsule { display: flex; align-items: center; margin-left: 30rpx; width: 140rpx; justify-content: space-between; height: 100%; }

    .navbar-v-line { width: 1px; height: 32rpx; background-color: #e5e5e5; }

    .back-pre, .back-home { width: 32rpx; height: 36rpx; margin-top: 4rpx; padding: 10rpx; transform: rotate(180deg); } .nav-capsule .back-home { width: 36rpx; height: 40rpx; margin-top: 3rpx; }

使用方法

  • 引入组件使用

app.json全局引入

 "usingComponents": {   "navWrap":"/components/Common/navwrap/navwrap"  },

 .wxml

<navWrap navbarData='{{nvabarData}}'/>

   .js

data:{
   nvabarData: {      title: '楼盘详情',      showCapsule: true,    }, //头部信息
}