跳到主要内容

设备 API

如何判断用户设备

答案
方法主要原理优点局限典型代码
User-Agent分析解析navigator.userAgent字符串实现简单,兼容性好易被伪造,部分设备难区分/mobile/i.test(ua)
视口尺寸判断检测window.innerWidth无需依赖UA,适合响应式横屏/分屏等场景不准width<768
媒体查询window.matchMedia结合CSS断点与响应式设计一致仅能判断尺寸,非设备类型matchMedia('(max-width:767px)')

核心概念与原理

  • User-Agent(UA)字符串包含浏览器、系统、设备等信息,常用于初步判断设备类型,但易被修改或伪造。
  • 视口尺寸法通过检测窗口宽度推断设备类别,适合响应式布局,但对特殊场景(如横屏、缩放)不够精确。
  • 媒体查询法利用 CSS 断点,结合 JS 的 window.matchMedia,可动态判断当前视口是否符合某类设备标准。

代码示例

// 1. User-Agent 判断
function detectDevice () {
const ua = navigator.userAgent
if (/mobile/i.test(ua)) return 'Mobile'
if (/tablet/i.test(ua)) return 'Tablet'
if (/iPad|iPhone|iPod/.test(ua)) return 'iOS Device'
return 'Desktop'
}

// 2. 视口尺寸判断
function detectDeviceByViewport () {
const w = window.innerWidth
if (w < 768) return 'Mobile'
if (w < 992) return 'Tablet'
return 'Desktop'
}

// 3. 媒体查询判断
function detectDeviceByMediaQuery () {
if (window.matchMedia('(max-width:767px)').matches) return 'Mobile'
if (window.matchMedia('(min-width:768px) and (max-width:991px)').matches) return 'Tablet'
return 'Desktop'
}

常见误区与开发建议

  • UA 检测不可靠,仅适合作为辅助手段,不能作为安全或唯一依据。
  • 视口尺寸和媒体查询更适合响应式布局,建议优先采用“自适应内容”而非“设备定制”。
  • 设备检测应结合多种手段,避免因单一方法导致误判。

延伸阅读

48%