判断 PC 端还是移动端
使用 JavaScript 判断页面是通过 PC 端还是移动端访问
问题
如何判断页面是通过 PC 端还是移动端访问?
解答
方法一:navigator.userAgent
通过分析浏览器的 user agent 字符串判断设备类型。
if (/Mobi|Android|iPhone/i.test(navigator.userAgent)) {
// 当前设备是移动设备
}
// 另一种写法
if (
navigator.userAgent.match(/Mobi/i) ||
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/iPhone/i)
) {
// 当前设备是移动设备
}
Chromium 系浏览器支持 navigator.userAgentData 属性:
const isMobile = navigator.userAgentData.mobile;
注意:Safari 和 Firefox 不支持此属性。
也可以使用已废除但兼容性好的 navigator.platform:
if (/Android|iPhone|iPad|iPod/i.test(navigator.platform)) {
// 当前设备是移动设备
}
方法二:屏幕宽度
通过 window.screen.width 或 window.innerWidth 判断。
if (window.screen.width < 500) {
// 当前设备是移动设备
}
根据不同宽度返回设备类型:
const getBrowserWidth = function() {
if (window.innerWidth < 768) {
return "xs";
} else if (window.innerWidth < 991) {
return "sm";
} else if (window.innerWidth < 1199) {
return "md";
} else {
return "lg";
}
};
方法三:window.orientation
检测屏幕方向属性,只有移动设备才有此属性。
if (typeof window.orientation !== 'undefined') {
// 当前设备是移动设备
}
注意:iPhone 的 Safari 不支持该属性。
方法四:touch 事件
检测是否支持触摸事件。
function isMobile() {
return ('ontouchstart' in document.documentElement);
}
// 另一种写法
function isMobile() {
try {
document.createEvent("TouchEvent");
return true;
} catch(e) {
return false;
}
}
方法五:window.matchMedia()
结合 CSS media query 判断。
let isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;
通过指针精确性判断:
let isMobile = window.matchMedia("(any-pointer:coarse)").matches;
any-pointer:coarse 表示存在不精确的指针(如触摸屏)。
方法六:使用工具包
推荐使用 react-device-detect:
import {isMobile} from 'react-device-detect';
if (isMobile) {
// 当前设备是移动设备
}
关键点
navigator.userAgent最简单但可被伪造,不够可靠- 屏幕宽度判断适合响应式布局,但横屏时可能误判
window.orientation和 touch 事件检测更准确,但存在兼容性问题window.matchMedia()结合 CSS media query 是较为可靠的方案- 生产环境建议使用成熟的工具包如
react-device-detect
目录