JavaScript 判断 iPhone X 系列机型的正确方法
针对 iPhone X 及后续机型底部安全区域适配问题,分析传统分辨率判断的局限性。本文提供基于设备像素比、屏幕尺寸及 User Agent 的综合检测方案,并介绍媒体查询与 JavaScript 结合的使用注意事项,确保 H5 页面在 iOS 长屏设备上的兼容性与准确性。
iPhone X 系列适配背景
前言
若存在更优的实现方案,欢迎交流指正。
背景说明
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 系列新设备的发布,原有的判断方式已无法覆盖所有机型。
iPhone X 系列设备参数分析
iPhone X 系列设备参数详情
| 机型 | 倍率 | 分辨率 | 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 X 之后的机型均需进行适配,可将该系列设备视为具有“iOS 系统”与“长屏幕”特征的整体进行统一处理。
在 H5 开发中可采用简化处理方式。
const isIphonex = () => {
if (typeof window !== 'undefined' && window) {
return /iphone/gi.test(window.navigator.userAgent) && window.screen.height >= 812;
}
return false;
};
使用媒体查询(Media Queries)
@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 系统,需配合 JavaScript 判断,否则可能误判部分安卓设备。
以上内容为本文核心观点,旨在为相关开发工作提供参考。
JavaScript异步发送HTTP请求时怎么优雅地处理错误
2026-11-05 17:10:44
5款主流JS在线运行工具对比:CodePen、JSFiddle与StackBlitz怎么选
2026-11-05 17:04:04
JavaScript入门书籍避坑:这些书不适合初学者
2026-11-05 16:31:15
JS使用Math.round实现保留两位小数的原理与代码
2026-11-05 15:35:55
JavaScript 原生 Date 对象怎么实现日期加减
2026-11-05 14:30:00
