微信小程序自定义导航栏

app.json中设置自定义导航栏:"navigationStyle": "custom"

{
    "pages": [
        // 单页面配置
        {
            "path": "pages/index/index",
            "style": {
                "navigationStyle": "custom"
            }
        }
    ],
    // 全局配置
    "window": {
        "navigationStyle": "custom"
    }
}

app.js中获取设备和胶囊的信息:

123.png
App({
    globalData: {},
    onLaunch() {
        // 获取胶囊按钮的信息 
        let menuButtonObject = wx.getMenuButtonBoundingClientRect()
        // 获取设备信息
        wx.getSystemInfo({
            success: res => {
                let statusBarHeight = res.statusBarHeight, // 获取状态栏的高度
                    navTop = menuButtonObject.top, // 胶囊按钮与顶部的距离
                    navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2, // 整个导航栏高度
                    navRight = res.windowWidth - menuButtonObject.right // 胶囊按钮与右侧的距离
                this.globalData.navHeight = navHeight
                this.globalData.navTop = navTop
                this.globalData.navRight = navRight
                this.globalData.menuButtonHeight = menuButtonObject.height
            },
            fail: err => {
                console.log(err);
            }
        })
    }
})

index.wxml:

<view class="sticky nav" style="height:{{navHeight}}px;padding-top:{{navTop}}px;padding-left:{{navRight}}px;line-height: {{menuButtonHeight}}px;">
</view>

index.js:

const app = getApp()

Page({
    data: {
        navHeight: app.globalData.navHeight,  // 整个导航栏高度
        navTop: app.globalData.navTop, // 胶囊按钮与顶部的距离
        navRight: app.globalData.navRight, // 胶囊按钮与右侧的距离
        menuButtonHeight: app.globalData.menuButtonHeight // 胶囊的高度
    }
})

index.wxss:

.nav{
  box-sizing: border-box;
}

/* 吸顶 */
// 小程序
.sticky {
    position: sticky;
    top: 0;
    z-index: 5;
}
// uni-app
.sticky {
    position: sticky;
    /* #ifdef H5 */
    top: var(--window-top);
    /* #endif */
    /* #ifndef H5 */
    top: 0;
    /* #endif */
    z-index: 5;
}

PS.多页面需要使用最好把它封成一个组件

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容