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

最近公司小程序有个需求 简单来说就是除开首页和我的页面
其他页面左上角都需要有一个返回按钮 能返回首页 最开始我说的是不用做 那两个tabbar页面 下面可以点啊
结果客户那边非得要 没办法 客户就是上帝

那么 话不多说 我们直接开干

首先是新建一个custom-navbar组件 目录结构如下

image.png

然后就是考虑到每个机型的状态栏高度不一样 所以需要用wx提供的getSystemInfoSync api
获取到statusBarHeight 状态栏的高度 就是手机电池电量那个区域的高度

    const { statusBarHeight } = wx.getSystemInfoSync();
    this.globalData.statusBarHeight = statusBarHeight;

拿到statusBarHeight后 可以编写custom-navbar.wxml

<!-- custom-navbar.wxml --> 
<view class="navbar" style="height: {{statusBarHeight + 44}}px"> 
  <view class="navbar-content" style="top: {{statusBarHeight}}px;height: 44px;">
    <view class="navbar-left" style="cursor: pointer;" bindtap="goBack">  
      <image src="/assets/img/left.png"></image>
    </view>  
    <view class="navbar-title">{{title}}</view> 
    <view class="navbar-right" style="opacity: 0;">
      <image src="/assets/img/left.png"></image>
    </view>
  </view>  
</view>

statusBarHeight + 44 44是状态栏下面 顶部的高度

image.png

对应的custom-navbar.js

// custom-navbar.js 
const app = getApp() 
Component({  
  properties: {  
    title: {  
      type: String,  
      value: '页面标题'  
    }  
  },
  data:{
    statusBarHeight: app.globalData.statusBarHeight,
  },  
  methods: {  
    goBack() {  
      wx.switchTab({
        url: "../home/home",
      })
    }  
  },
});

以及custom-navbar.wxss

/* custom-navbar.wxss */  
.navbar {  
  display: flex;  
  justify-content: space-between;  
  align-items: center;  
  background-color: #AB2917;  
  position: fixed;  
  top: 0;  
  left: 0;  
  right: 0;  
  z-index: 10;  
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1); /* 简单的阴影效果 */  
}   
  
.navbar-left image,  
.navbar-right image {  
  width: 100%;  
  height: 100%;  
} 

.navbar-left ,  
.navbar-right {  
  width: 24px;  
  height: 24px;  
} 
.navbar-right{
  margin-right: 10px;
}  
.navbar-left{
  margin-left: 10px;
} 
.navbar-title {  
  text-align: center;  
  font-size: 36rpx; /* 标题字体大小 */  
  color: white;  
  overflow: hidden;  
  text-overflow: ellipsis;  
  white-space: nowrap; /* 确保标题过长时能够截断并显示省略号 */  
  background-color: #AB2917; 
}  
.navbar-content{
  width: 750rpx;
  background-color: #AB2917; 
  position: fixed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.navbar-content view{
  background-color: #AB2917; 
}

好的 那么 组件写完了就是在页面上使用了 记得在页面的json中声明navigationStyle=“custom” 表示使用自定义导航栏哦 顺便引用组件(如果要全局使用 就要在app.json中写)

{
  "usingComponents": {  
    "custom-navbar": "../../component/custom-navbar/custom-navbar"  
  },  
  "navigationStyle":"custom"
}

千万记得调整一下页面的margin-top哦

<view class="clear">
      <custom-navbar title="视频专区"></custom-navbar>
      <view `style="margin-top: {{44 + statusHeight + 10 }}px;`"></view> /*一定一定一定要记得加 10是离状态栏+顶部的高度*/
</view>      

本人写这篇文章的初衷是记录 方便以后用到的时候可以直接来找
如果有写的不对的地方 欢迎评论区留言

posted @ 2024-08-02 18:13  前端小李子  阅读(1496)  评论(0)    收藏  举报