如何使用JavaScript来判断是否为移动设备

855次阅读
没有评论

共计 2057 个字符,预计需要花费 6 分钟才能阅读完成。

由于移动设备的显示屏幕相对于桌面显示器来说小很多,在桌面显示器上能够正常显示的内容,到了移动设备中就不正常了。为了实现移动端和桌面端的相互跳转,我们可以通过 JavaScript 来判断当前的设备是否是移动设备,然后执行相应的代码。

通过 js 来判断当前的设备

下面的代码片段能够检测 6 种不同的移动设备:

if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {// 执行相应代码或直接跳转到手机页面} else {// 执行桌面端代码}

上面的 js 代码可以判断当前设备是否是 Android、iPhone 或 iPad 等六种移动设备中的一种。如果你需要单独检测当前设备是否是某种指定的设备,例如是否是 iPhone,可以使用下面的代码:

if(iPhone.test(navigator.userAgent) ) {alert("这是 iPhone 设备");
} else {alert("不是 iPhone 设备");
}
通过 device.js 来判断当前的设备

device.js是一个用于检查设备操作系统的 js 插件。使用它可以检测 iOS, Android, Blackberry, Windows, Firefox OS, MeeGo, AppleTV 等系统,还可以判断当前的设备是横向的还是纵向的。

device.js 会在你的页面 <html> 元素中插入相应的 class 类,例如:

如何使用 JavaScript 来判断是否为移动设备 在 iphone 中使用 device.js
如何使用 JavaScript 来判断是否为移动设备 在 Android 平板中使用 device.js
在蓝莓系统中使用 device.js

device.js 支持的设备有:

  • iOS: iPhone, iPod, iPad
  • Android: Phones & Tablets
  • Blackberry: Phones & Tablets
  • Windows: Phones & Tablets
  • Firefox OS: Phones & Tablets

使用 device.js 插件的方法是在页面中引入 device.js 文件,在浏览器解析页面时,根据当前的设备,device.js 就会在 <html> 元素中插入不同的 class 类。这些 class 类对应的设备如下表所示:

设备名称 class 类
iPad ios ipad tablet
iPhone ios iphone mobile
iPod ios ipod mobile
Android Phone android mobile
Android Tablet android tablet
BlackBerry Phone blackberry mobile
BlackBerry Tablet blackberry tablet
Windows Phone windows mobile
Windows Tablet windows tablet
Firefox OS Phone fxos mobile
Firefox OS Tablet fxos tablet
MeeGo meego
Desktop desktop
Television television

根据当前设备屏幕是横向还是纵向的,device.js 会在 <html> 元素中插入相应的 class 类。

设备方向 class 类
Landscape landscape
Portrait portrait

另外,device.js 还提供了一组用于判断设备的 js 方法,使用方法如下:

if(device.mobile()){// 执行移动设备的方法}

所有可用的判断方法如下表所示:

设备名称 JavaScript 方法
Mobile device.mobile()
Tablet device.tablet()
Desktop device.desktop()
iOS device.ios()
iPad device.ipad()
iPhone device.iphone()
iPod device.ipod()
Android device.android()
Android Phone device.androidPhone()
Android Tablet device.androidTablet()
BlackBerry device.blackberry()
BlackBerry Phone device.blackberryPhone()
BlackBerry Tablet device.blackberryTablet()
Windows device.windows()
Windows Phone device.windowsPhone()
Windows Tablet device.windowsTablet()
Firefox OS device.fxos()
Firefox OS Phone device.fxosPhone()
Firefox OS Tablet device.fxosTablet()
MeeGo device.meego()
Television device.television()

判断设备方向的 js 方法有:

设备方向 JavaScript 方法
Landscape device.landscape()
Portrait device.portrait()
正文完
 0