小程序计算nav-bar

在app.js中进行计算,之后放入全局,封装component,放入全局组件直接使用
计算公式:statusBarHeight + height + (top - statusBarHeight) * 2

onlunch() {
  // 获取状态栏高度
  const { statusBarHeight } = wx.getSystemInfoSync();

  // 得到右上角菜单的位置尺寸
  const menuButtonObject = wx.getMenuButtonBoundingClientRect();
  const { top, height } = menuButtonObject;

  // 计算导航栏的高度
  // 此高度基于右上角菜单在导航栏位置垂直居中计算得到
  const navBarHeight = height + (top - statusBarHeight) * 2;

  // 计算状态栏与导航栏的总高度
  const statusNavBarHeight = statusBarHeight + navBarHeight;
  this.globalData.statusNavBarHeight = statusNavBarHeight;
  this.globalData.navBarHeight = navBarHeight;
  this.globalData.statusBarHeight = statusBarHeight;
},
globalData: {
  statusNavBarHeight: 0,
  navBarHeight: 0,
  statusBarHeight: 0,
}  

封装组件

<view class="nav" style="height:{{statusNavBarHeight}}px;">
  <view class="nav_con" style="height:{{navBarHeight}}px;top: {{statusBarHeight}}px;">
    <view class="left_con">
      <image src="./back.png" bindtap="backTrigger" class="back" wx:if="{{back}}" />
      <slot name="left">
      </slot>
    </view>
    <view class="nav_title">
      {{title}}
    </view>
    <view class="right_con">
      <slot name="right"></slot>
    </view>
  </view>
</view>
/* components/navbar/navbar.wxss */
.nav {
  width: 100%;
  background-color: #fff;
  position: sticky;
  z-index: 9;
  top: 0;
  padding: 0 30rpx;
  box-sizing: border-box;
}
.left_con,
.right_con,
.nav_title {
  vertical-align: middle;
  height: 100%;
  display: flex;
  align-items: center;
}
.left_con .back {
  width: 30rpx;
  height: 30rpx;
  vertical-align: middle;
}
.nav_con {
  position: relative;
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  align-items: center;
}
.nav_title {
  text-align: center;
  justify-content: center;
  font-weight: 500;
  font-size: 36rpx;
  color: #000000;
  letter-spacing: 0;
  overflow: hidden;
}
const app = getApp();
Component({
  options: {
    multipleSlots: true,
  },
  properties: {
    title: {
      type: String,
      optionalTypes: [Number, null],
    },
    back: {
      type: Boolean,
      value: false,
    },
  },
  lifetimes: {
    attached() {
      let {
        statusNavBarHeight,
        navBarHeight,
        statusBarHeight,
      } = app.globalData;
      this.setData({
        statusNavBarHeight,
        navBarHeight,
        statusBarHeight,
      });
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    statusNavBarHeight: 0,
    navBarHeight: 0,
    statusBarHeight: 0,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    backTrigger() {
      let that = this;
      wx.navigateBack({
        delta: 1,
        fail() {
          that.triggerEvnet("back");
        },
      });
    },
  },
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值