检查返回我是否在智能手机上的 JavaScript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11013778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:49:02  来源:igfitidea点击:

A check in JavaScript that returns whether I am on a smartphone?

javascriptjquerydevice-detection

提问by Dave Haigh

I want to perform a check in one of my JavaScript functions that determines whether I am on a smartphone and then decide whether or not to run the function based on the results.

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

What is the best way to detect/check for a smartphone (or handheld device in general) in JavaScript?

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

e.g.

例如

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

If there is not one definite method to check for a phone, then what are the best selection of checks I should to perform before deciding which code to run?

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

EDIT/UPDATE:The answers and comments on this similar post should give me something to go on - What is the best way to detect a mobile device in jQuery?

编辑/更新:这篇类似帖子的答案和评论应该让我有所收获 -在 jQuery 中检测移动设备的最佳方法是什么?

回答by primavera133

Ye olde browser sniffing seems to be the solution

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

回答by kotekzot

You can use the CategorizrJS library to test whether the user's device is a mobile phone, a tablet, a smart tv or a desktop. Categorizr uses user agent sniffing, so you should keep an eye out for updates to the script, as user agents tend to "evolve" over time.

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

Here's how you would use Categorizr to check if the user is on a smartphone, but not a smart TV, a desktop or a tablet:

以下是您将如何使用 Categorizr 检查用户是否使用智能手机,而不是智能电视、台式机或平板电脑:

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

回答by Vinnyq12

You could try twitter bootstrap, http://twitter.github.com/bootstrap/scaffolding.html. In particular the Responsive design section.

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