关于uni-app开发的微信小程序顶部导航条机型适配

468 阅读2分钟

背景:

小程序顶部导航栏那里的样式和功能都是小程序自带的,当我们在pages.json里的pages里新加一条页面配置时,会自动生成一个带顶部导航栏的空白页面,当然也可以再配置里"navigationBarTitleText","navigationBarTextStyle","navigationBarBackgroundColor",来改变导航栏标题字体,标题字体颜色,导航栏背景颜色,其实上面那些配置一般的应用场景下够用了, 但是有时候产品就偏偏不想用他的默认样式, 想在那里放张背景图, 放个输入框, 放个按钮啥的,这时候就需要自定义导航条了

实现:

  1. pages.json里配置navigationStyle为custom
            "path": "pages/index/index",
            "pageOrientation": "landscape",
            "style": {
                "navigationStyle":"custom",
            }
        }

2 如上配置好后即可实现自定义导航栏,不过直接写的话会有机型样式的差异, 如iPhoneX等机型的刘海屏会遮住部分内容,处理办法是获取导航栏信息,根据小程序右上角的胶囊定位, 代码如下

onLaunch: function() {// 获取系统信息
            const systemInfo = uni.getSystemInfoSync();
            // 获取胶囊按钮的位置
            const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
            // 导航栏高度 = 状态栏到胶囊的间距( 胶囊距上距离 - 状态栏高度 )*2  +  胶囊高度  +  状态栏高度
            this.globalData.navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + menuButtonInfo
                .height + systemInfo.statusBarHeight;
            this.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
            this.globalData.menuBotton = menuButtonInfo.top - systemInfo.statusBarHeight;
            this.globalData.menuHeight = menuButtonInfo.height;
    },
    globalData: {
        navBarHeight: </span>0, <span style="color: #008000;">//</span><span style="color: #008000;"> 导航栏高度</span>
        menuRight: 0, <span style="color: #008000;">//</span><span style="color: #008000;"> 胶囊距右方间距(方保持左、右间距一致)</span>
        menuBotton: 0, <span style="color: #008000;">//</span><span style="color: #008000;"> 胶囊距底部间距(保持底部间距一致)</span>
        menuHeight: 0, <span style="color: #008000;">//</span><span style="color: #008000;"> 胶囊高度(自定义内容可与胶囊高度保证一致)</span>
    }

这样就获取到了所需信息并存到了globalData全局变量里
在页面或组件里用到这些信息

export default {
        data() {
            return {
                // 机型顶部适配
                navBarHeight: getApp().globalData.navBarHeight,
                menuRight: getApp().globalData.menuRight,
                menuBotton: getApp().globalData.menuBotton,
                menuHeight: getApp().globalData.menuHeight,
               
            }
    }
}

3 思路如上, 部分样式代码没贴上去自行添加即可