溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

JavaScript 判斷iPhone X Series機型的方法

發布時間:2020-09-16 23:08:15 來源:腳本之家 閱讀:321 作者:axuebin 欄目:web開發

寫在前面

如果有更優雅的方式,一定要告訴我!

現狀

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

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

// h6
export const isIphonex = () => /iphone/gi.test(navigator.userAgent) && window.screen && (window.screen.height === 812 && window.screen.width === 375);

這在之前是沒問題的,新的 iPhone X Series 設備發布之后,這個就會兼容就有問題。

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 就無能為力了。

解決方法

對每個機型進行判斷

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,
 },
 ];
 // h6
 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 + 長臉。

在 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 判斷,否則可能會誤判一些安卓機。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女