如何编写仅适配iPad Safari的CSS媒体查询?
如何仅针对iPad Safari应用特定CSS样式
嘿,要实现只给iPad Safari应用这段样式,咱们可以用JavaScript检测浏览器标识 + CSS类定位的方案,这比纯CSS媒体查询更精准——毕竟现在iPad上的Chrome、Firefox也用WebKit内核,纯CSS很难区分它们和Safari。
下面是具体步骤:
步骤1:添加浏览器检测的JavaScript代码
在页面的<script>标签(或者你的外部JS文件)里加入这段代码,它会精准识别iPad Safari,并给页面的body标签添加一个专属类:
// 精准检测iPad Safari const isIPadSafari = /iPad/.test(navigator.userAgent) && /Safari/.test(navigator.userAgent) && !/CriOS/.test(navigator.userAgent) // 排除iPad Chrome && !/FxiOS/.test(navigator.userAgent); // 排除iPad Firefox if (isIPadSafari) { document.body.classList.add('is-ipad-safari'); }
代码解释:
/iPad/.test(navigator.userAgent):先判断设备是iPad/Safari/.test(navigator.userAgent):确认浏览器包含Safari标识!/CriOS/.test(navigator.userAgent):排除iPad上的Chrome(CriOS是Chrome iOS的专属标识)!/FxiOS/.test(navigator.userAgent):排除iPad上的Firefox(FxiOS是Firefox iOS的专属标识)
步骤2:编写针对性的CSS样式
现在你只需要把原来的CSS样式加上咱们刚才添加的类前缀,就能确保它只在iPad Safari上生效了:
/* 仅iPad Safari生效的样式 */ .is-ipad-safari .et_pb_contact_right p input.et_pb_content_captcha { font-weight: bold; border: 2px #F7823A solid; }
备选:纯CSS方案(精度稍低)
如果你不想用JS,也可以尝试纯CSS的组合查询,但要注意:现在iPad上的Chrome也是WebKit内核,这个方案可能会误匹配,仅作参考:
@media only screen and (min-width: 768px) and (max-width: 1024px) { /* 匹配WebKit内核,排除IE、Firefox */ @supports (-webkit-touch-callout: none) and (not (-ms-ime-align: auto)) and (not (-moz-appearance: none)) { .et_pb_contact_right p input.et_pb_content_captcha { font-weight: bold; border: 2px #F7823A solid; } } }
这个方案通过屏幕尺寸锁定iPad,再用@supports筛选WebKit内核且排除其他浏览器,但因为iPad Chrome也是WebKit,所以可能会同时生效,所以更推荐前面的JS+CSS方案。
内容的提问来源于stack exchange,提问作者tangobango
相关产品推荐
相关产品推荐

