如何判断页面是通过PC端还是移动端访问?
参考答案
1. UA 判断(主流但有局限)
const ua = navigator.userAgent;
const isMobile = /Android|iPhone|iPad|iPod|HarmonyOS|Mobile/i.test(ua);
局限:UA 可伪造、iPadOS 伪装成 Mac、新设备型号繁杂。
2. 特征检测(更可靠)
- 触屏:
'ontouchstart' in window/navigator.maxTouchPoints > 0 - 指针:
matchMedia('(hover: none), (pointer: coarse)') - 屏幕尺寸:
screen.width、window.innerWidth
3. 响应式(最佳实践)
不判断设备,用媒体查询/容器查询 + 弹性布局自适应,同一份代码适配所有尺寸。
4. 服务端判断
读 User-Agent/Sec-CH-UA-Mobile 请求头,返回不同页面(CDN 层也可)。
结论:能用响应式就不要靠 UA 硬分流;确需分流时 UA + 特征双校验。