> 技术文档 > uniapp之自定义小程序导航栏_uniapp 自定义导航栏

uniapp之自定义小程序导航栏_uniapp 自定义导航栏


目录

  • 一、自定义须知
    • 1.状态栏和导航栏的区别
    • 2.官方使用注意
    • 3.getMenuButtonBoundingClientRect返参详解
  • 二、效果展示
    • 1.demo下载地址
  • 三、实现步骤
    • 1.在pages.json中进行配置(自定义生效的前提)
    • 2.vue代码
  • 四、拓展与思考
  • 五、总结

一、自定义须知

1.状态栏和导航栏的区别

在这里插入图片描述

2.官方使用注意

官方地址:https://uniapp.dcloud.net.cn/collocation/pages.html#customnav

在这里插入图片描述

3.getMenuButtonBoundingClientRect返参详解

属性 说明 图解 width 宽度,单位:px uniapp之自定义小程序导航栏_uniapp 自定义导航栏 height 高度,单位:px uniapp之自定义小程序导航栏_uniapp 自定义导航栏 top 上边界坐标,单位:px uniapp之自定义小程序导航栏_uniapp 自定义导航栏 right 右边界坐标,单位:px uniapp之自定义小程序导航栏_uniapp 自定义导航栏 bottom 下边界坐标,单位:px uniapp之自定义小程序导航栏_uniapp 自定义导航栏 left 左边界坐标,单位:px uniapp之自定义小程序导航栏_uniapp 自定义导航栏

二、效果展示

uniapp之自定义小程序导航栏_uniapp 自定义导航栏

1.demo下载地址

https://github.com/INIT1996/uniapp-demo


三、实现步骤

1.在pages.json中进行配置(自定义生效的前提)

{\"root\": \"navSubPage\",\"pages\": [{\"path\": \"index/index\",\"style\": {// 自定义导航栏生效的前提\"navigationStyle\": \"custom\"}}]}

2.vue代码

<template><view class=\"container\"><image class=\"bg\" src=\"../static/myBg.png\" mode=\"aspectFill\"></image><view class=\"bar_box\"><view class=\"status_bar\" :style=\"{height:statusBarHeight+\'px\'}\"></view><view class=\"nav_bar\" :style=\"{ height:navBarHeight+\'px\' }\">自定义nav</view></view></view></template><script setup>import {ref,onBeforeMount} from \'vue\';// 状态栏高度let statusBarHeight = ref(0);// 导航栏样式let navBarHeight = ref(0);onBeforeMount(() => {// 状态栏的高度statusBarHeight.value = uni.getSystemInfoSync()[\'statusBarHeight\'];// 获取胶囊的定位const custom = wx.getMenuButtonBoundingClientRect();// 导航栏的高度 = 胶囊的高度 + (胶囊最上侧距离手机顶部的高度 - 状态栏的高度)* 2navBarHeight.value = custom.height + (custom.top - statusBarHeight.value) * 2;});</script><style lang=\"less\" scoped>.container {height: 100vh;box-sizing: border-box;.bg {width: 100%;height: 45vh;position: fixed;}.bar_box {z-index: 1;position: relative;.nav_bar {color: #fff;display: flex;align-items: center;justify-content: center;}}}</style>

四、拓展与思考

// 自定义导航栏的实际宽度(扒除胶囊的部分)= 胶囊最左侧距离手机屏幕最左侧的距离let navBarWidth = custom.left;// 导航栏的左右边距 = 手机宽度 - 胶囊最右侧距离手机屏幕最左侧的距离let navPaddingLeft = systemInfo.screenWidth - customInfo.right;// 导航栏的上下边距 = 胶囊最上侧距离手机顶部的高度 - 状态栏的高度let navPaddingTop = custom.top - statusBarHeight.value;

五、总结

自定义导航栏的前提,是在pages.json文件中将navigationStyle设置为custom;
状态栏的高度可以直接通getSystemInfoSync获取;
导航栏的高度,等于胶囊的高度加上其上下边距,上下边距可以通过胶囊距离顶部的高度减去状态栏的高度进行获取;
导航栏的宽度,等于胶囊距离手机最左边的距离;
导航栏的左右边距,等于手机宽度减去胶囊最右侧距离手机屏幕最左侧的距离;
导航栏的上下边距,等于胶囊最上侧距离手机顶部的高度减去状态栏的高度;