文章目录
基础用法
下面方法适用于大多数情况。如果需要更精确的检测,可以考虑使用现成的库,如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端');
}
1521

被折叠的 条评论
为什么被折叠?



