Skip to content

自定义 navbar

json
{
  "pages": [
    {
      "path": "pages/index/index",
      "style": {
        "navigationStyle": "custom" // 使用自定义导航栏
      }
    }
  ]
}
vue
<template>
  <view class="custom-navbar">
    <view class="custom-navbar__wrap page-bg">
      <view class="custom-navbar-status" :style="{ height: `${statusBarHeight}px` }"></view>
      <view class="custom-navbar-title" :style="{ height: `${titleBarHeight}px` }"></view>
    </view>
    <view class="custom-navbar-fill" :style="{ height: `${statusBarHeight + titleBarHeight}px` }"></view>
  </view>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { getStatusBarHeight, getTitleBarHeight } from '@/utils/system.js'

const statusBarHeight = getStatusBarHeight()
const titleBarHeight = getTitleBarHeight()
</script>

<style lang="scss" scoped>
.custom-navbar {
  .custom-navbar__wrap {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
    width: 100%;
    background-color: darkorange;
  }
}
</style>
js
export function getStatusBarHeight() {
  const SYSTEM_INFO = uni.getSystemInfoSync()
  return SYSTEM_INFO.statusBarHeight || 0
}

export function getTitleBarHeight() {
  // #ifdef H5
  return 44
  // #endif

  // #ifndef H5
  const SYSTEM_INFO = uni.getSystemInfoSync()
  const MENU_BUTTON = uni.getMenuButtonBoundingClientRect()
  const { top, height } = MENU_BUTTON
  const { statusBarHeight } = SYSTEM_INFO
  const gap = top - statusBarHeight
  return height + gap * 3
  // #endif
}

提示

navbar 高度为 44px (不含状态栏)。

常用 api:

  • uni.getSystemInfoSync:同步获取系统信息。

    • statusBarHeight:手机状态栏的高度。
  • uni.getMenuButtonBoundingClientRect:获取胶囊按钮的布局位置信息。

    • width:宽度,单位:px
    • height:高度,单位:px
    • top:上边界坐标,单位:px
    • right:右边界坐标,单位:px
    • bottom:下边界坐标,单位:px
    • left:左边界坐标,单位:px
  • 当选择了自定义 navbar 之后,pull-down refresh loading 需要自行实现。

基于 MIT 许可发布