【JS】区分移动端和PC端方法
文章目录
- 基础用法
基础用法
下面方法适用于大多数情况。如果需要更精确的检测,可以考虑使用现成的库,如Modernizr
、mobile-detect.js
等
function isMobile() {// 检查用户代理字符串const userAgent = navigator.userAgent || navigator.vendor || window.opera;// 常见的移动设备用户代理关键字const mobileAgents = ['Android', 'iPhone', 'iPad', 'iPod', 'BlackBerry', 'Windows Phone', 'webOS', 'Mobile', 'IEMobile'];// 如果用户代理中包含任何移动设备关键字,则认为是移动端if (mobileAgents.some(agent => userAgent.includes(agent))) {return true;}// 检查触摸支持if ('maxTouchPoints' in navigator && navigator.maxTouchPoints > 0) {return true;}// 其他情况,默认为PC端return false;
}// 使用示例
if (isMobile()) {console.log('这是移动端');
} else {console.log('这是PC端');
}