前端瀏覽器判斷設備類型的方法
在前端開發中,判斷設備類型(如手機、平板、桌面電腦)有多種方法,以下是常用的幾種方式:
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" 等