html判断是苹果,JavaScript判断是否是iPhone X系列机型,H5和其他环境兼容

最近遇到的iPhone X全面屏的刘海适配问题,由于浏览器或者APP全屏显示时,刘海会遮住原页面顶部的信息。

68f32f1be92b096e93f28e2033710a36.png

所以如何判断手机是 iPhone X 呢?

利用 JavaScript 实现:

其中的一个普遍的方法是:function isIphoneX(){

return /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375)

}

先通过返回的布尔值判断会否是 iPhone X ,然后再进行操作:比如给头部一个上边距,一般是44px。if (isIphoneX) {

$("header").css("margin-top","44px");

......

}

前端页面兼容 iPhone X 的刘海,我会在下一篇文章详细总结。

另一种写法,博主也测试成功:iphone 测试失败,改为 iPhone 后返回 true 了。var isIphoneX = /iPhone[\s\S]*OS X/.test(navigator.userAgent)

还找到一个方法:

现状

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 参数机型倍率分辨率ptiPhone X32436 × 1125812 × 375

iPhone XS32436 × 1125812 × 375

iPhone XS Max32688 × 1242896 × 414

iPhone XR21792 × 828896 × 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 判断,否则可能会误判一些安卓机。

参考文献:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值