前端浏览器判断设备类型的方法
前端浏览器判断设备类型的方法
在前端开发中,判断设备类型(如手机、平板、桌面电脑)有多种方法,以下是常用的几种方式:
1. 使用 User Agent 检测
通过 navigator.userAgent
获取用户代理字符串进行判断:
function getDeviceType() {const ua = navigator.userAgent;if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {return "tablet";}if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {return "mobile";}return "desktop";
}
2. 使用屏幕尺寸检测(响应式设计常用)
function getDeviceType() {const width = window.innerWidth;if (width < 768) {return 'mobile';} else if (width >= 768 && width < 1024) {return 'tablet';} else {return 'desktop';}
}
3. 使用现代 API 检测
使用 navigator.maxTouchPoints
function isTouchDevice() {return (('ontouchstart' in window) ||(navigator.maxTouchPoints > 0) ||(navigator.msMaxTouchPoints > 0));
}
使用媒体查询 (Media Queries)
function checkDeviceType() {if (window.matchMedia("(max-width: 767px)").matches) {return 'mobile';} else if (window.matchMedia("(min-width: 768px) and (max-width: 1023px)").matches) {return 'tablet';} else {return 'desktop';}
}
4. 使用 CSS 媒体查询结合 JavaScript
/* CSS */
@media (max-width: 767px) {body:after {content: 'mobile';display: none;}
}
@media (min-width: 768px) and (max-width: 1023px) {body:after {content: 'tablet';display: none;}
}
@media (min-width: 1024px) {body:after {content: 'desktop';display: none;}
}
// JavaScript
function getDeviceType() {return window.getComputedStyle(document.body, ':after').content.replace(/"/g, '');
}
5. 使用第三方库
- Modernizr: 功能检测库
- UAParser.js: 专业的 User Agent 解析库
- react-device-detect: React 设备检测库
// 使用 UAParser.js 示例
const parser = new UAParser();
const result = parser.getResult();
console.log(result.device.type); // "mobile", "tablet", "console", "smarttv" 等