屏幕兼容齐刘海

“jingle bells, jingle bells Jingle all the way …”
作为一名前端开发工程师,我们经常需要适配不同的机型,在这里我们可以使用 safe-area-insets 这个插件解决屏幕齐刘海的问题,它让我们可以使用 js 来获取安全区信息

但是有两个先决条件:

  1. WKWebview(IOS 8之后出现,相比UIWebView,WKWebView优化了较 多的体验)
  2. viewport-fit=cover(视图端口被缩放以填充设备显示)

安装:

npm install safe-area-insets --save

使用:

var safeAreaInsets = require('safe-area-insets')

安全区信息:

console.log('safeAreaInsets.support', safeAreaInsets.support) // 是否支持
console.log('safe-area-inset-top', safeAreaInsets.top) // top
console.log('safe-area-inset-left', safeAreaInsets.left) // left
console.log('safe-area-inset-right', safeAreaInsets.right) // right
console.log('safe-area-inset-bottom', safeAreaInsets.bottom) // bottom

监听安全区信息变化事件:

function callback(style){
    console.log(style) // 样式信息
    console.log(style.top) // top
    console.log(style.bottom) // bottom
}
// add 添加监听回调函数
safeAreaInsets.onChange(callback)
// remove 移除监听回调函数
safeAreaInsets.offChange(callback)

在 vue 中使用示例代码:

  1. style 中使用 data 中的变量,挂载完之后监听安全区域的位置
  2. 得到安全区域位置信息,改变 data 中变量的值
  3. 数据变化,视图改变,从而达到适配不同机型齐刘海的效果
<template>
<div id="app">
  <header class="header" :style="{'padding-top': paddingTop+'px'}">
    <h1 class="title">我的APP</h1>
  </header>
  
  <router-view :style="{top: 44+paddingTop+'px', bottom: 49+paddingBottom+'px'}">
  </router-view>

  <nav class="tabs" :style="{'padding-bottom': paddingBottom+'px'}">
    <router-link class="tab-item" to="/home">首页</router-link>
    <router-link class="tab-item" to="/category">分类</router-link>
    <router-link class="tab-item" to="/setting">设置</router-link>
  </nav>

</div>
</template>

<script>
var safeAreaInsets = require('safe-area-insets')

export default {
  data(){
    return {
      paddingTop: safeAreaInsets.top,
      paddingBottom: safeAreaInsets.bottom,
    }
  },
  created(){
    //挂载完之后监听安全区域的位置
    safeAreaInsets.onChange((style)=>{
        this.paddingTop = style.top;
        this.paddingBottom = style.bottom;
    })
  }

}
</script>

<style>
*{
  margin: 0;
  padding: 0;
}

html, body, #app{
  width: 100%;
  height: 100%;
  
  color: #333;
}
body{
  background: #42b983;
}
#app{
  background: #f1f1f1;
}
.header{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 44px;
  background: #42b983;
}
.title{
  width: 100%;
  height: 44px;
  line-height: 44px;
  text-align: center;
  font-size: 16px;
  color: #fff;
  background: #42b983;
}
.page{
  width: 100%;
  position: absolute;
  left: 0;
  top: 44px;
  bottom: 49px;
}
.tabs{
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 49px;
  background: #42b983;
  display: flex;
}
.tab-item{
  flex: 1;
  list-style: none;
  color: #fff;
  text-align: center;
  line-height: 49px;
  font-weight: bold;
}
</style>

oh what fun it’s to ride in a one horse open sleigh ~
骑着麋鹿走啦,略略略 ~

发布了20 篇原创文章 · 获赞 29 · 访问量 818

猜你喜欢

转载自blog.csdn.net/weixin_44691775/article/details/104429298