当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript 判断iPhone X Series机型的方法

JavaScript 判断iPhone X Series机型的方法

2019年03月17日  | 移动技术网IT编程  | 我要评论

写在前面

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

现状

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) {
}

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网