🔄 兼容性处理
移动端浏览器的兼容性问题主要集中在iOS Safari、Android WebView、微信内置浏览器。
各浏览器常见坑点
| 浏览器 | 常见问题 | 解决方案 |
|---|---|---|
| iOS Safari | 不支持 WebP(iOS 14-)、Date 解析差异、position:fixed 在键盘弹出时异常 | 图片兜底 JPG/PNG、使用 dayjs 处理日期、避免 fixed 在输入场景 |
| Android 微信 | 不支持 ES6 Module、缓存策略激进、长按图片会弹出菜单 | 打包为 ES5、加版本号/v参数控制缓存、用 CSS 禁止长按 |
| iOS 微信 | 音频视频自动播放限制、scroll 事件不连续触发 | 需要用户手势触发播放、使用 IntersectionObserver 替代 |
| 各厂商 WebView | 内核版本低、不支持新 CSS/JS 特性 | 使用 Babel + Autoprefixer、特性检测 + Polyfill |
常用兼容性写法
/* ===== 移动端兼容性常用代码 ===== */
/* ① 禁止 iOS 长按弹出菜单 */
* {
-webkit-touch-callout: none; /* iOS 长按链接菜单 */
-webkit-user-select: none; /* 禁止选中文字 */
user-select: none;
}
input, textarea {
-webkit-user-select: auto; /* 输入框允许选中 */
user-select: auto;
}
/* ② 禁止图片长按保存(微信) */
img {
-webkit-touch-callout: none;
pointer-events: none; /* 简单粗暴 */
}
/* ③ iOS 输入框圆角重置 */
input, textarea {
-webkit-appearance: none;
border-radius: 0;
}
/* ④ 去除点击高亮背景 */
* {
-webkit-tap-highlight-color: transparent;
}
/* ⑤ 安全区域兼容写法 */
.fixed-bottom {
padding-bottom: constant(safe-area-inset-bottom); /* iOS 11.0-11.2 */
padding-bottom: env(safe-area-inset-bottom); /* iOS 11.2+ */
}
JS 兼容处理
// ===== 移动端 JS 兼容处理 =====
// ① 特性检测(优于 UA 判断)
if ('geolocation' in navigator) {
// 支持定位
}
if (window.IntersectionObserver) {
// 支持懒加载
}
// ② 微信环境判断
const isWeChat = /MicroMessenger/i.test(navigator.userAgent);
// ③ iOS 版本判断
function getIOSVersion() {
const match = navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
if (match) {
return parseInt(match[1], 10);
}
return 0;
}
// ④ 低版本浏览器 Promise polyfill
if (typeof Promise === 'undefined') {
// 动态加载 polyfill
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/promise-polyfill@8/dist/polyfill.min.js';
document.head.appendChild(script);
}