【问题标题】:A check in JavaScript that returns whether I am on a smartphone? [duplicate]检查是否返回我是否在智能手机上的 JavaScript? [复制]
【发布时间】:2012-06-16 08:17:56
【问题描述】:

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

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

例如

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

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

编辑/更新:这个类似帖子上的答案和 cmets 应该给我一些继续 - What is the best way to detect a mobile device in jQuery?

【问题讨论】:

标签: javascript jquery device-detection


【解决方案1】:

老旧的浏览器嗅探似乎是解决方案

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..
}

【讨论】:

  • 我在上面发布的链接上有这个答案的副本。
  • 是的,我无耻地从那里偷了它。认为作为问题的实际答案可能值得多强调一下。
【解决方案2】:

你可以试试 twitter 引导程序,http://twitter.github.com/bootstrap/scaffolding.html。特别是响应式设计部分。

【讨论】:

【解决方案3】:

您可以使用Categorizr JS库来测试用户的设备是手机、平板、智能电视还是台式机。 Categorizr 使用用户代理嗅探,因此您应该留意脚本的更新,因为用户代理会随着时间的推移而“演变”。

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

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

【讨论】:

    猜你喜欢
    • 2017-02-28
    • 2020-05-08
    • 2013-10-17
    • 2018-03-27
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    相关资源
    最近更新 更多