首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >微信小程序自定义状态栏

微信小程序自定义状态栏

作者头像
渔父歌
发布2019-03-15 14:30:18
1.8K0
发布2019-03-15 14:30:18
举报
文章被收录于专栏:数据结构笔记数据结构笔记

首先修改 app.json文件中的 windows字段如下:

{
    "pages": [
        "pages/index/index"
    ],
    "window": {
        "navigationStyle": "custom"
    }
}

为了避免遮挡用户手机顶部状态栏,还需要获取用户手机状态栏的高度,并在在每个页面中添加一个占位用的 view标签来防止遮挡用户状态栏。

在 app.js文件添加如下代码:

App({
   onLaunch: function() {
       wx.getSystemInfo({
           success: res=> {
               this.globalData.navHeight = res.statusBarHeight;
           },
       })
   },
   globalData: {
       userInfo: null,
       navHeight: 0,
   }
})

在每个页面中添加一个占位用的 view标签,背景色与自定义的状态栏的背景色相同。

不过自定义的状态栏背景色一般不要设置成黑色或者白色,因为大多数手机的状态栏字体颜色就是黑色和白色。

js文件、wxml文件和wxss文件如下:

//index.js
const app = getApp()

Page({
    data: {
        //从全局变量获取状态栏高度
        navHeight: app.globalData.navHeight,
    },
    onLoad: function () {
    },
    getUserInfo: function (e) {
        console.log(e)
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    }
})
<!--index.wxml-->
<view class='palce-holder-nav' style="height: {{navHeight}}px;"></view>
/*app.wxss*/
.palce-holder-nav{
    width: 100%;
    background-color: red;
}

显示效果如下:

最后就可以在下面添加自定义的状态栏,自定义状态栏的高度一般刚好超过胶囊的下边, 这个高度大概是系统状态栏的2倍。

代码如下:

<!--index.wxml-->
<view class='palce-holder-nav' style="height: {{navHeight}}px;"></view>
<view class='palce-holder-nav' style="height: {{2*navHeight}}px;"></view>

显示效果如下:

使用的时候在外面再包裹一层view标签:

<!--index.wxml-->
<view class='custom-navbar'>
   <view class='palce-holder-nav' style="height: {{navHeight}}px;"></view>
   <view class='title' style="height: {{2*navHeight}}px;"></view>
</view>
/*app.wxss*/
.custom-navbar{
    width: 100%;
    background-color: red;
}
.palce-holder-nav{
    width: 100%;
}

甚至还可以弄出居中标题的效果:

//index.js
const app = getApp()

Page({
    data: {
        navHeight: app.globalData.navHeight,
        title: '这是一个居中标题'
    },
    onLoad: function () {
    },
})
<!--index.wxml-->
<view class='custom-navbar'>
    <view class='palce-holder-nav' style="height: {{navHeight}}px;"></view>
    <view class='title' style="height: {{2*navHeight}}px;">
        <view>{{title}}</view>
    </view>
</view>
/*app.wxss*/
.custom-navbar{
    width: 100%;
    background-color: red;
}
.palce-holder-nav{
    width: 100%;
}
.title{
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
.title>view{
    width: fit-content;
    color: white;
}

效果图:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.03.09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档