屏幕兼容齊劉海

“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 ~
騎着麋鹿走啦,略略略 ~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章