JavaScript 判斷 iPhone X Series 機型

原文連接:JavaScript 判斷 iPhone X Series 機型javascript

寫在前面

若是有更優雅的方式,必定要告訴我!css

現狀

iPhone X 底部是須要預留 34px 的安全距離,須要在代碼中進行兼容。java

現狀對於 iPhone X 的判斷基本是這樣的:ios

// h5
export const isIphonex = () => /iphone/gi.test(navigator.userAgent) && window.screen && (window.screen.height === 812 && window.screen.width === 375);
複製代碼

這在以前是沒問題的,新的 iPhone X Series 設備發佈以後,這個就會兼容就有問題。git

iPhone X Series 參數

機型 倍率 分辨率 pt
iPhone X 3 2436 × 1125 812 × 375
iPhone XS 3 2436 × 1125 812 × 375
iPhone XS Max 3 2688 × 1242 896 × 414
iPhone XR 2 1792 × 828 896 × 414

width === 375 && height === 812 只能識別出 iPhone X 和 iPhone XS,對於 iPhone XS Max 和 iPhone XR 就無能爲力了。github

解決方法

對每一個機型進行判斷

const isIphonex = () => {
  // X XS, XS Max, XR
  const xSeriesConfig = [
    {
      devicePixelRatio: 3,
      width: 375,
      height: 812,
    },
    {
      devicePixelRatio: 3,
      width: 414,
      height: 896,
    },
    {
      devicePixelRatio: 2,
      width: 414,
      height: 896,
    },
  ];
  // h5
  if (typeof window !== 'undefined' && window) {
    const isIOS = /iphone/gi.test(window.navigator.userAgent);
    if (!isIOS) return false;
    const { devicePixelRatio, screen } = window;
    const { width, height } = screen;
    return xSeriesConfig.some(item => item.devicePixelRatio === devicePixelRatio && item.width === width && item.height === height);
  }
  return false;
}
複製代碼

統一處理方法

由於如今 iPhone 在 iPhone X 以後的機型都須要適配,因此能夠對 X 之後的機型統一處理,咱們能夠認爲這系列手機的特徵是 ios + 長臉web

在 H5 上能夠簡單處理。安全

const isIphonex = () => {
  if (typeof window !== 'undefined' && window) {
    return /iphone/gi.test(window.navigator.userAgent) && window.screen.height >= 812;
  }
  return false;
};
複製代碼

媒體查詢

@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
}
@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 3) {
}
@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2) {
}
複製代碼

媒體查詢沒法識別是否是 iOS,還得加一層 JS 判斷,不然可能會誤判一些安卓機。iphone

相關文章
相關標籤/搜索