视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
JavaScript 判断iPhone X Series机型的方法
2020-11-27 22:01:37 责编:小采
文档


写在前面

如果有更优雅的方式,一定要告诉我!

现状

iPhone X 底部是需要预留 34px 的安全距离,需要在代码中进行兼容。

现状对于 iPhone X 的判断基本是这样的:

// h5
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 6 × 414
iPhone XR 2 1792 × 828 6 × 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: 6,
 },
 {
 devicePixelRatio: 2,
 width: 414,
 height: 6,
 },
 ];
 // 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 + 长脸。

在 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: 6px) and (-webkit-device-pixel-ratio: 3) {
}
@media only screen and (device-width: 414px) and (device-height: 6px) and (-webkit-device-pixel-ratio: 2) {
}

媒体查询无法识别是不是 iOS,还得加一层 JS 判断,否则可能会误判一些安卓机。

下载本文
显示全文
专题