小程序自定义导航栏与高度适配的问题

365 阅读1分钟

在小程序中有一个单位是rpx既为responsive pixel,当750既为所有宽度的手机都能适配为满屏相当于100vw或者100%(得配置page页面)

那高度呢?

1.盒子铺满整个屏幕

page {
  display: flex;
  flex-direction: column;
  /* flex: 1; */
  height: 100vh;
  /* background: #000; */
}
.box{
  background: blue;
  flex: 1;
}

//wxml
<view class="box"></view>

当然 你也可以直接在box内使用100vh 效果 414x869 (iphone xs max)

image.png

320x568(iphone 5)

image.png

2.自定义导航栏

当遇到自定义导航栏的需求时会遇到这样的问题

image.png

如果使用rpx单位去配置将会遇到样式问题

正确做法是使用wx.getMenuButtonBoundingClientRect()与 wx.getSystemInfo()这两个api

前者是获取右上角胶囊的宽高于上下左右的位置 后者可以获取到statusBarHeight(状态栏高度)

所以 自定义导航栏遇到的样式bug大多出自于每个手机的statusBarHeight不一样

解决思路就是让设计两个盒子

一个用于fixed定位 一个用于加高度占位

fixed定位的盒子填写你需要的内容 加高度占位的不需要

注意 都需要填写width:750rpx铺满盒子

//js部分  lifetimes是自定义组件的内容 在页面上课换成onLoad函数内编写
  lifetimes: {
    attached() {
      const res = wx.getSystemInfoSync();
      console.log(res.statusBarHeight);
      const menu = wx.getMenuButtonBoundingClientRect();
      console.log(menu);
      const menuPX = menu.top - res.statusBarHeight;
      this.setData({
        statusBar: res.statusBarHeight,
        meun: menu.height + menuPX * 2,
      });
    },
  },
  data: {
    statusBar: 0,
    meun: 0,
  },
  //wxml
<wxs src="./nav.wxs" module="nav" />
<view class="nav" style="{{nav.setHeaderCss(statusBar,meun,bgColor)}}">
	<view/>
	<text>首页</text>
	<view/>
</view>
<view style="height:{{ statusBar+meun }}px;width:750rpx" />
//wxs
function setHeaderCss(height, menu, bgColor) {
  var res =
    "padding-top:" + height + "px;height:" + menu + "px;background:" + bgColor;
  console.log(res);
  return res;
}