You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写仅对iPhone 14生效的CSS媒体查询?

区分iPhone 14与iPhone 15的CSS样式方案

由于iPhone 14和iPhone 15的视口尺寸、分辨率及设备像素比完全一致,纯CSS媒体查询无法直接区分二者。可通过JavaScript检测设备型号并添加专属类名的方式实现精准样式控制,具体步骤如下:

1. 用JavaScript检测设备并添加类名

在页面加载时,解析设备标识符判断机型,给根标签添加专属类:

function detectIphoneModel() {
    const userAgent = navigator.userAgent;
    // iPhone 14的设备标识符为iPhone15,2,iPhone 15为iPhone16,1
    if (userAgent.includes('iPhone15,2')) {
        document.documentElement.classList.add('is-iphone14');
    } else if (userAgent.includes('iPhone16,1')) {
        document.documentElement.classList.add('is-iphone15');
    }
}

window.addEventListener('load', detectIphoneModel);

注:设备标识符可通过实际测试或苹果官方设备文档确认,不同机型对应唯一标识符。

2. 针对专属类编写CSS样式

通过类名精准定位iPhone 14,避免样式冲突:

/* 仅作用于iPhone 14的竖屏样式 */
.is-iphone14 .Chat-section {
    gap: 10px;
    right: 2.5%;
    width: 95svw;
    width: 95vw;
    justify-content: flex-start;
}

/* 如需单独设置iPhone 15样式,可按同样逻辑编写 */
.is-iphone15 .Chat-section {
    /* iPhone 15专属样式 */
}

补充说明

纯CSS方案无法区分参数完全一致的设备,JS辅助是当前最可靠的解决途径。若担心userAgent被篡改,可结合env(safe-area-inset-top)等环境变量辅助判断,但精准度略低于设备标识符检测。

内容的提问来源于stack exchange,提问作者Vicknesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 03:24:57