app沉浸式导航栏相关处理(适用于Hbuilder打包项目)

2,172 阅读1分钟

在移动端,很多的app都需要设置沉浸式导航栏,但是手机适配又成了一个很大的问题。所以通过获取手机状态栏高度,再增加页面padding的方法应该是最好的,可以适应各种妖孽手机。首先需要在HBuilder的配置文件中设置沉浸式导航,找到manifest.json件下的plus对象,然后贴如下面代码:

	"statusbar": {
		"immersed": true/*沉浸式状态栏*/
	},

下面代码片段是获取移动端状态栏高度的。 注:此代码写在main.js中


//由于plus模块需要加载,所以这里我使用了延时处理

setTimeout(()=>{
  if(window.plus){
  //首先判断当前设备是否支持沉浸式导航栏,如果不支持不做处理
    var isImmersedStatusbar = plus.navigator.isImmersedStatusbar();
    if (isImmersedStatusbar) {
	    //获取当前设备状态栏高度
        var StatusbarHeight = plus.navigator.getStatusbarHeight();
        //当前机型如果是iPhoneX,则在原基础上增加15像素。
        //获取到高度后在vue的原型上增加StatusbarHeight属性,方便后续使用
        if (plus.device.model.toString() == 'iPhoneX') {
            Vue.prototype.$StatusbarHeight = StatusbarHeight + 15;
        } else {
            Vue.prototype.$StatusbarHeight = StatusbarHeight;
        }
    }
    //此处设置了状态栏文字的颜色---dark为黑色/light为白色
    plus.navigator.setStatusBarStyle('dark');
	//在处理结束后页面再出来,否则会出现抖动现象
    new Vue({
      el: '#app',
      router,
      store,
      components: { App },
      template: '<App/>'
    })
  }
},100)

在获取到高度后,在app.vue页面来给#app增加padding值,这里一劳永逸型,哈哈。

	:style="{paddingTop:`${$StatusbarHeight}px`}"

如果有个别状态栏背景色不一样的,可以给#app动态添加class来解决,改变#app背景色

    document.getElementById('app').className += '自定义class名字'