天天看點

H5 iOS新機型适配前言問題解決方案

前言

近期在做落地頁優化項目中,針對iOS多種新機型(iPhone X之後的劉海屏)适配,有一些坑點,及适配相關的心得,在此記錄一下

問題

落地頁首屏頁面要求鋪滿全屏,背景圖撐滿。之前設計稿都是750 * 1134,但是為了适配iPhone X(分辨率375 * 812)類的劉海屏手機,UI多出了一份750 * 1642的設計稿,那麼頁面首屏的高度需要是螢幕高度,背景圖要按兩套背景圖來,而由于該項目裡區分國家,是以一共是2套*3國,6套背景圖

解決方案

方案一

首屏dom高度設定為100vh

.first-screen{
      position relative
      width 100%
      height 100vh
      background-size 100% 100%
      background-repeat no-repeat
      background-position center
      margin 0 0 1.26rem
}
           

但是設定vh的方式,在webview頁面打開是沒有問題的,在iOS Safari浏覽器打開,頁面下半部分會被導覽列擋住,如圖所示

H5 iOS新機型适配前言問題解決方案

查閱資料發現100vh在Safari浏覽器上會遇到各種問題,如果你的頁面隻在webview内打開,使用這種布局是沒有問題的,但是我的項目是同時需要在webview和浏覽器内打開的,是以這種方法不可取

方案二

使用window.innerHeight擷取螢幕高度,動态設定dom高度

html部分

<div
      v-if="config.firstScreen"
      :style="{
        'background-image': `url(${firstScreenBg})`,
        'height': firstScreenHeight
      }"
      class="first-screen part">
           

js部分

const innerHeight = window.innerHeight
...
    data() {
      return {
        logoSrc,
        config: {},
        inited: false,
        firstScreenHeight: `${innerHeight}px`
      };
    },
    computed:{
      firstScreenBg(){
        //針對iOS 375*812 414*896 390*884 428*926螢幕配置對應的背景圖
        return (isIPhoneX || isIPhone11 || isIPhone12 || isIPhone12ProMax) ? this.countryUtil.getConfig('getGuides')().imgForIphoneX : this.countryUtil.getConfig('getGuides')().img
      }
    },  
...    
           

判斷是否是iPhone X或者iPhone 11等機型

const { devicePixelRatio, screen } = window;
const { width, height } = screen;
export const isIPhoneX = isIOS && (width === 375 && height === 812 && devicePixelRatio === 3) //iphoneX、iphoneXs、iphone11 Pro
export const isIPhone11 = isIOS && (width === 414 && height === 896 && devicePixelRatio === 3) //iphone Xs Max、iphone11、iphone11 Pro Max
export const isIPhone12 = isIOS && (width === 390 && height === 844 && devicePixelRatio === 3)
export const isIPhone12ProMax = isIOS && (width === 428 && height === 926 && devicePixelRatio === 3)
           

由于頁面最底部按鈕需要針對劉海屏機型的底部做适配,是以需要用到env(safe-area-inset-bottom)

.register-btn{
      margin 0.4rem
      &.bottom{
        margin-bottom calc(.4rem + env(safe-area-inset-bottom)) //針對劉海屏機型适配
      }
    }
           

參考

https://zhuanlan.zhihu.com/p/369515213