实际例子
通过实际案例加深对设备兼容的理解。
典型兼容问题及解决方案
| 场景 | 问题描述 | 解决方案 |
|---|---|---|
| 300ms点击延迟 | iOS Safari点击有延迟 | 设置viewport禁用缩放 或使用fastclick |
| iOS橡皮筋效果 | 页面滚动到底部仍可滚动 | -webkit-overflow-scrolling:touch |
| Android键盘遮挡 | 输入框被键盘遮挡 | 监听resize事件,调整布局 |
| input样式不一致 | 不同浏览器input样式不同 | 重置样式或使用自定义组件 |
| Retina图片模糊 | dpr>1时图片模糊 | 使用2x图片或srcset |
| video全屏播放 | iOS/Android全屏方式不同 | 使用webkitenterfullscreen |
移动端兼容示例
// 1. 禁止iOS橡皮筋效果
body {
position: fixed;
width: 100%;
}
// 2. 解决Android输入框键盘遮挡
window.addEventListener('resize', function() {
const scrollHeight = document.documentElement.scrollHeight;
const clientHeight = document.documentElement.clientHeight;
if (scrollHeight > clientHeight) {
// 滚动到底部
window.scrollTo(0, scrollHeight - clientHeight);
}
});
// 3. 解决iOS点击延迟 - FastClick
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function() {
FastClick.attach(document.body);
}, false);
}
// 4. Retina屏幕图片处理
function getRetinaImage(src) {
const dpr = window.devicePixelRatio || 1;
if (dpr > 1) {
const ext = src.split('.').pop();
const base = src.slice(0, -ext.length - 1);
return `${base}@${dpr}x.${ext}`;
}
return src;
}
// 5. 处理iOS和Android的video差异
function playVideo(video) {
if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
video.play();
} else {
video.webkitEnterFullscreen();
video.play();
}
}