JavaScript 判断 iPhone X Series 机型

栏目: IOS · 发布时间: 5年前

内容简介:iPhone X 底部是需要预留 34px 的安全距离,需要在代码中进行兼容。现状对于 iPhone X 的判断基本是这样的:这在之前是没问题的,新的 iPhone X Series 设备发布之后,这个就会兼容就有问题。

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 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,
    },
  ];
  // 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: 896px) and (-webkit-device-pixel-ratio: 3) {
}
@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2) {
}
复制代码

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


以上所述就是小编给大家介绍的《JavaScript 判断 iPhone X Series 机型》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

科技投资新时代:TMT投资方法、趋势与热点聚焦

科技投资新时代:TMT投资方法、趋势与热点聚焦

马军、宋辉、段迎晟 / 人民邮电出版社 / 2018-3 / 69.00

中国 TMT 行业(科技、媒体及通信)起步较晚但充满朝气。2017 年,TMT 板块的IPO 数量占到了总数的四分之一;对于投资者来说,投资 TMT 的收益非常可观。那么,TMT 的投资趋势如何? TMT 行业又有哪些投资热点? 本书立足于 TMT 投资现状,在介绍了 TMT 投资的基本概念之后,作者详细讲述了TMT 投资的基本研究方法、分析视角、整体行情及趋势分析,同时从行业视角分析了包括......一起来看看 《科技投资新时代:TMT投资方法、趋势与热点聚焦》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试