检查JavaScript是否返回智能手机?

我想对我的一个JavaScript函数执行检查,以确定我是否在智能手机上,然后根据结果决定是否运行该函数。

在JavaScript中检测/检查智能手机(或一般手持设备)的最佳方法是什么?

例如

if (user is on a smartphone) { //run this code if on a phone } else { //run this code if not on a phone } 

如果没有一种明确的方法可以检查手机,那么在决定运行哪些代码之前,我应该选择哪些最佳检查?

编辑/更新:这篇相似post的答案和评论应该让我有所作为 – 在jQuery中检测移动设备的最佳方法是什么?

Ye olde浏览器嗅探似乎是解决方案

 if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) ){ // some code.. } 

您可以尝试使用twitter bootstrap, http://twitter.github.com/bootstrap/scaffolding.html 。 特别是响应式设计部分。

您可以使用Categorizr JS库来测试用户的设备是手机,平板电脑,智能电视还是桌面。 分类程序使用用户代理嗅探,因此您应该留意脚本的更新,因为用户代理往往会随着时间的推移而“发展”。

以下是使用Categorizr检查用户是否在智能手机上,而不是智能电视,台式机或平板电脑的方法:

 if (categorizr.isMobile) { //run this code if on a phone } else { //run this code if not on a phone }