前端怎么区分不同电脑设备信息
时间: 2023-11-27 09:52:02 浏览: 31
前端可以通过浏览器提供的 `navigator` 对象来获取设备信息,例如设备类型、操作系统、浏览器等。以下是一些示例代码:
1. 获取设备类型:
```javascript
const isMobile = /Mobi/i.test(navigator.userAgent);
console.log(isMobile ? '移动设备' : '桌面设备');
```
2. 获取操作系统:
```javascript
const os = navigator.platform;
console.log(os);
```
3. 获取浏览器信息:
```javascript
const browser = (() => {
const ua = navigator.userAgent.toLowerCase();
const match = /(edge)\/([\w.]+)/.exec(ua) ||
/(chrome)\/([\w.]+)/.exec(ua) ||
/(firefox)\/([\w.]+)/.exec(ua) ||
/(opera)\/([\w.]+)/.exec(ua) ||
/(iemobile)\/([\w.]+)/.exec(ua) ||
/(version)(applewebkit|trident)(?:.*)(safari|rv:([\w.]+)|)/.exec(ua) ||
[];
const platformMatch = /(ipad)/.exec(ua) ||
/(iphone)/.exec(ua) ||
/(android)/.exec(ua) ||
/(windows phone)/.exec(ua) ||
/(win)/.exec(ua) ||
/(mac)/.exec(ua) ||
/(linux)/.exec(ua) ||
/(cros)/.exec(ua) ||
[];
return {
browser: match[3] || match[1] || '',
version: match[2] || '0',
platform: platformMatch[0] || ''
};
})();
console.log(browser);
```
通过这些代码,你可以获取到设备类型、操作系统和浏览器信息,然后根据这些信息来进行相应的适配。