如何使用 jQuery 检测移动设备
有没有办法在 jQuery 中检测用户是否正在使用移动设备?类似于 CSS @media
属性?如果浏览器位于手持设备上,我想运行不同的脚本。
jQuery $.browser
函数不是我正在寻找的。
Is there a way to detect whether or not a user is using a mobile device in jQuery? Something similar to the CSS @media
attribute? I would like to run a different script if the browser is on a handheld device.
The jQuery $.browser
function is not what I am looking for.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
编者注:对于现代 Web 应用程序,不建议使用用户代理检测技术。请参阅此答案下面的评论以确认这一事实。建议使用特征检测和/或媒体查询来使用其他答案之一。
您可以使用简单的 JavaScript 来检测它,而不是使用 jQuery:
或者您可以将它们结合起来,以便通过 jQuery 更容易访问它...
现在
$.browser
将返回"device" 适用于所有上述设备
注意:
$.browser
已在 jQuery v1.9.1。但是您可以通过使用 jQuery 迁移插件 代码更彻底的版本来使用它:
Editor's note: user agent detection is not a recommended technique for modern web apps. See the comments below this answer for confirmation of this fact. It is suggested to use one of the other answers using feature detection and/or media queries.
Instead of using jQuery you can use simple JavaScript to detect it:
Or you can combine them both to make it more accessible through jQuery...
Now
$.browser
will return"device"
for all above devicesNote:
$.browser
removed on jQuery v1.9.1. But you can use this by using jQuery migration plugin CodeA more thorough version:
对我来说,小就是美,所以我使用这种技术:
在 CSS 文件中:
在 jQuery/JavaScript 文件中:
我的目标是让我的网站“适合移动设备”。所以我使用 CSS 媒体查询根据屏幕尺寸显示/隐藏元素。
例如,在我的移动版本中,我不想激活 Facebook Like Box,因为它会加载所有这些个人资料图片和内容。这对于移动访问者来说并不好。因此,除了隐藏容器元素之外,我还在 jQuery 代码块(上面)中执行此操作:
您可以在 http:// /lisboaautentica.com
我仍在开发移动版本,所以在撰写本文时,它看起来仍然没有达到应有的效果。
由 dekin88 更新
有一个内置的 JavaScript API 用于检测媒体。
不使用上述解决方案,只需使用以下内容:
浏览器支持: http://caniuse .com/#feat=matchmedia
这种方法的优点是它不仅更简单、更短,而且如果需要,您可以有条件地分别针对不同的设备,例如智能手机和平板电脑,而无需在 DOM 中添加任何虚拟元素。
For me small is beautiful so I'm using this technique:
In CSS file:
In jQuery/JavaScript file:
My objective was to have my site "mobile-friendly". So I use CSS Media Queries do show/hide elements depending on the screen size.
For example, in my mobile version I don't want to activate the Facebook Like Box, because it loads all those profile images and stuff. And that's not good for mobile visitors. So, besides hiding the container element, I also do this inside the jQuery code block (above):
You can see it in action at http://lisboaautentica.com
I'm still working on the the mobile version, so it's still not looking as it should, as of writing this.
Update by dekin88
There is a JavaScript API built-in for detecting media.
Rather than using the above solution simply use the following:
Browser Supports: http://caniuse.com/#feat=matchmedia
The advantage of this method is that it's not only simpler and shorter, but you can conditionally target different devices such as smartphones and tablets separately if necessary without having to add any dummy elements into the DOM.
虽然 Mozilla 使用用户代理的浏览器检测现在建议不要使用此解决方案:
它曾经推荐:
像这样:
这将匹配所有常见的移动浏览器用户代理,包括移动 Mozilla、Safari、IE、Opera、Chrome 等。
Android 更新
EricL 建议针对
Android
进行测试,如下所示还包括用户代理,因为平板电脑的 Chrome 用户代理字符串不包括“Mobi”(但是手机版本可以):While Mozilla's Browser detection using the user agent now recommends against this solution:
it used to recommend:
Like this:
This will match all common mobile browser user agents, including mobile Mozilla, Safari, IE, Opera, Chrome, etc.
Update for Android
EricL recommends testing for
Android
as a user agent also, as the Chrome user agent string for tablets does not include "Mobi" (the phone versions do however):简单而有效的一句:
但是上面的代码没有考虑带触摸屏的笔记本电脑的情况。
因此,我提供了基于 @Julian 解决方案的第二个版本:
A simple and effective one-liner:
However above code doesn't take into account the case for laptops with touchscreen.
Thus, I provide this second version, based on @Julian solution:
它不是 jQuery,但我发现了这个: http://detectmobilebrowser.com/
它提供了脚本来检测多个移动浏览器语言,其中之一是 JavaScript。这可能会帮助您找到您正在寻找的东西。
但是,由于您使用的是 jQuery,因此您可能需要了解 jQuery.support 集合。它是用于检测当前浏览器功能的属性集合。文档位于: http://api.jquery.com/jQuery.support/
自从我不知道你到底想要实现什么,我不知道其中哪一个最有用。
话虽这么说,我认为最好的选择是使用服务器端语言重定向或编写不同的脚本到输出(如果这是一个选项)。由于您并不真正了解移动浏览器x的功能,因此在服务器端进行检测和更改逻辑将是最可靠的方法。当然,如果您不能使用服务器端语言,那么所有这些都是没有意义的:)
It's not jQuery, but I found this: http://detectmobilebrowser.com/
It provides scripts to detect mobile browsers in several languages, one of which is JavaScript. That may help you with what you're looking for.
However, since you are using jQuery, you might want to be aware of the jQuery.support collection. It's a collection of properties for detecting the capabilities of the current browser. Documentation is here: http://api.jquery.com/jQuery.support/
Since I don't know what exactly what you're trying to accomplish, I don't know which of these will be the most useful.
All that being said, I think your best bet is to either redirect or write a different script to the output using a server-side language (if that is an option). Since you don't really know the capabilities of a mobile browser x, doing the detection, and alteration logic on the server side would be the most reliable method. Of course, all of that is a moot point if you can't use a server side language :)
有时需要知道客户正在使用哪个品牌的设备,以便显示特定于该设备的内容,例如 iPhone 商店或 Android 市场的链接。 Modernizer 很棒,但只向您展示浏览器功能,例如 HTML5 或 Flash。
这是我在 jQuery 中的 UserAgent 解决方案,用于为每种设备类型显示不同的类:
该解决方案来自 Graphics Maniacs
http:// Graphicmaniacs.com/note/detecting-iphone-ipod-ipad-android-and-blackberry-browser-with-javascript-and-php/
Sometimes it is desired to know which brand device a client is using in order to show content specific to that device, like a link to the iPhone store or the Android market. Modernizer is great, but only shows you browser capabilities, like HTML5, or Flash.
Here is my UserAgent solution in jQuery to display a different class for each device type:
This solution is from Graphics Maniacs
http://graphicmaniacs.com/note/detecting-iphone-ipod-ipad-android-and-blackberry-browser-with-javascript-and-php/
找到了解决方案: http://www.abeautifulsite .net/blog/2011/11/Detecting-mobile-devices-with-javascript/。
然后要验证它是否是移动设备,您可以使用以下方法进行测试:
Found a solution in: http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/.
And then to verify if its a Mobile, you can test using:
如果“移动”指的是“小屏幕”,我会使用这个:
在 iPhone 上,最终的 window.screen.width 为 320。在 Android 上,最终的 window.outerWidth 为 480(尽管如此)可能取决于 Android)。 iPad 和 Android 平板电脑将返回 768 等数字,因此它们将获得您想要的完整视图。
If by "mobile" you mean "small screen," I use this:
On iPhone you'll end up with a window.screen.width of 320. On Android you'll end up with a window.outerWidth of 480 (though that can depend on the Android). iPads and Android tablets will return numbers like 768 so they'll get the full view like you'd want.
在一行 javascript 中:
如果用户代理包含“Mobi”(根据 MDN)并且 ontouchstart 可用,那么它很可能是移动设备。
编辑:更新正则表达式代码以响应评论中的反馈。使用正则表达式
/mobi/i
i 使其不区分大小写,并且 mobi 匹配所有移动浏览器。请参阅 https://developer.mozilla.org/ en-US/docs/Web/HTTP/Headers/User-Agent/FirefoxIn one line of javascript:
If the user agent contains 'Mobi' (as per MDN) and ontouchstart is available then it is likely to be a mobile device.
EDIT: Updates the regex code in response to feedback in the comments. Using regex
/mobi/i
the i makes it case-insensitive, and mobi matches all mobile browsers. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox我知道这个问题有很多答案,但从我所看到的来看,没有人以我解决这个问题的方式来接近答案。
CSS 使用宽度(媒体查询)来根据宽度确定应用于 Web 文档的样式。为什么不在 JavaScript 中使用宽度?
例如,在 Bootstrap 的(移动优先)媒体查询中,存在 4 个捕捉/断点:
我们也可以用它来解决 JavaScript 问题。
首先,我们将创建一个获取窗口大小并返回一个值的函数,该值允许我们查看正在查看我们的应用程序的设备的大小:
现在我们已经设置了该函数,我们可以调用它并存储该值:
您的问题是
现在我们有了设备信息,剩下的就是一个 if 语句:
这是 CodePen 上的示例: http://codepen.io/jacob-king/pen/jWEeWG
I know this question has a lot of answers, but from what I saw nobody approaches the answer the way I would solve this.
CSS uses width (Media Queries) to determine which styles applied to the web document baseed on width. Why not use width in the JavaScript?
For instance in Bootstrap's (Mobile First) Media Queries, there exist 4 snap/break points:
We can use this to also solve our JavaScript issue as well.
First we will create a function that gets the window size and returns a value that allows us to see what size device is viewing our application:
Now that we have the function set up, we can call it ans store the value:
Your question was
Now that we have the device information all that is left is an if statement:
Here is an example on CodePen: http://codepen.io/jacob-king/pen/jWEeWG
您不能依赖
navigator.userAgent
,并非每个设备都会显示其真正的操作系统。例如,在我的 HTC 上,这取决于设置(“使用移动版本”开/关)。在 http://my.clockodo.com 上,我们只是使用
screen.width
来检测小型设备。不幸的是,在某些 Android 版本中,screen.width 存在错误。您可以将此方式与 userAgent 结合使用:You can't rely on
navigator.userAgent
, not every device reveals its real OS. On my HTC for example, it depends on the settings ("using mobile version" on/off).On http://my.clockodo.com, we simply used
screen.width
to detect small devices. Unfortunately, in some Android versions there's a bug with screen.width. You can combine this way with the userAgent:如果您使用 Modernizr,那么使用前面提到的
Modernizr.touch
非常容易。不过,为了安全起见,我更喜欢结合使用 Modernizr.touch 和用户代理测试。
如果您不使用 Modernizr,则只需将上面的
Modernizr.touch
函数替换为('ontouchstart' in document.documentElement)
另请注意,测试用户代理 < code>iemobile 将为您提供比
Windows Phone
更广泛的检测到的 Microsoft 移动设备。另请参阅这个问题
If you use Modernizr, it is very easy to use
Modernizr.touch
as mentioned earlier.However, I prefer using a combination of
Modernizr.touch
and user agent testing, just to be safe.If you don't use Modernizr, you can simply replace the
Modernizr.touch
function above with('ontouchstart' in document.documentElement)
Also note that testing the user agent
iemobile
will give you broader range of detected Microsoft mobile devices thanWindows Phone
.Also see this SO question
我很惊讶没有人指出一个不错的网站: http://detectmobilebrowsers.com/ 它已经在中准备好了代码用于移动检测的不同语言(包括但不限于):
如果您还需要检测平板电脑,只需检查“关于”部分以获取其他 RegEx 参数。
I am surprised that no one pointed out a nice site: http://detectmobilebrowsers.com/ It has ready made code in different languages for mobile detection (including but not limited to):
And if you need to detect the tablets as well, just check About section for additional RegEx parameter.
如果您不是特别担心小显示器,您可以使用宽度/高度检测。这样,如果宽度低于一定大小,移动网站就会被抛出。它可能不是完美的方法,但它可能是最容易检测多个设备的方法。您可能需要为 iPhone 4(大分辨率)输入特定的一个。
If you're not particularly worried about small displays you could use width/height detection. So that way if width is under a certain size, the mobile site is thrown up. It may not be the perfect way, but it will probably be the easiest to detect for multiple devices. You may need to put in a specific one for the iPhone 4 (large resolution).
如果发现仅检查
navigator.userAgent
并不总是可靠。通过检查navigator.platform
可以获得更高的可靠性。对之前的答案进行简单修改似乎效果更好:If found that just checking
navigator.userAgent
isn't always reliable. Greater reliability can be achieved by also checkingnavigator.platform
. A simple modification to a previous answer seems to work better:为了添加额外的控制层,我使用 HTML5 存储来检测它是使用移动存储还是桌面存储。如果浏览器不支持存储,我有一个移动浏览器名称数组,并将用户代理与数组中的浏览器进行比较。
这很简单。这是函数:
To add an extra layer of control I use the HTML5 storage to detect if it is using mobile storage or desktop storage. If the browser does not support storage I have an array of mobile browser names and I compare the user agent with the browsers in the array.
It is pretty simple. Here is the function:
我建议您查看 http://wurfl.io/
简而言之,如果您导入一个很小的 JavaScript 文件:
您将得到一个如下所示的 JSON 对象:(
当然,假设您使用的是 Nexus 7),您将能够执行以下操作:
这就是您正在寻找的内容。
免责声明:我为提供此免费服务的公司工作。
I advise you check out http://wurfl.io/
In a nutshell, if you import a tiny JavaScript file:
You will be left with a JSON object that looks like:
(That's assuming you are using a Nexus 7, of course) and you will be able to do things like:
This is what you are looking for.
Disclaimer: I work for the company that offers this free service.
很好的答案,谢谢。支持 Windows Phone 和 Zune 的小改进:
Great answer thanks. Small improvement to support Windows phone and Zune:
我知道这是关于这种检测的一个非常古老的问题。
我的解决方案基于滚动条宽度(是否存在)。
I know it's very old question about this kind of detection.
My solution is based on scroller width (is exist or not).
看看这篇帖子,它提供了一个非常好的代码片段有关检测到触摸设备时执行的操作或调用 touchstart 事件时执行的操作:
Check out this post, it gives a really nice code snippet for what to do when touch devices are detected or what to do if touchstart event is called:
使用这个:
然后使用这个:
Use this:
Then use this:
所有答案都使用用户代理来检测浏览器,但基于用户代理的设备检测并不是很好的解决方案,更好的是检测触摸设备等功能(在新的 jQuery 中,他们删除
$.browser
并使用$.support
代替)。要检测移动设备,您可以检查触摸事件:
取自 使用 JavaScript 检测“触摸屏”设备的最佳方法是什么?
All answers use user-agent to detect the browser but device detection based on user-agent is not very good solution, better is to detect features like touch device (in new jQuery they remove
$.browser
and use$.support
instead).To detect mobile you can check for touch events:
Taken from What's the best way to detect a 'touch screen' device using JavaScript?
我建议使用以下字符串组合来检查是否正在使用设备类型。
根据 Mozilla 文档 string
Mobi
推荐。但是,如果仅使用Mobi
,一些旧的平板电脑不会返回 true,因此我们也应该使用Tablet
字符串。同样,为了安全起见,
iPad
和iPhone
字符串也可用于检查设备类型。大多数新设备都会仅针对
Mobi
字符串返回true
。I would be suggesting to use following combo of strings, to check if device type being used.
As per Mozilla documentation string
Mobi
is recommended. But, some of the old tablets doesn't return true if onlyMobi
is used, hence we should useTablet
string too.Similarly, for being on the safe side
iPad
andiPhone
strings could also be used to check the device type.Most of the new devices would return
true
forMobi
string alone.我知道这个老问题并且有很多答案,但我认为这个功能很简单,将有助于检测所有手机、平板电脑和计算机浏览器,它的工作方式就像一个魅力。
I know this old question and there is a lot of answer but I think this function is simple and will help for detect all mobile, Tablet and computer browser it work like a charm.
您可以使用以下函数来判断您是否在移动浏览器上运行。是的,它是浏览器嗅探,但有时这正是您所需要的。
Here's a function you can use to get a true/false answer as to whether you're running on a mobile browser. Yes, it is browser-sniffing, but sometimes that is exactly what you need.
基于 http://detectmobilebrowser.com/ 的简单功能
Simple function based on http://detectmobilebrowser.com/
如果您使用任何浏览器并尝试获取 navigator.userAgent,那么我们将获取类似于
Mozilla/5.0(Macintosh;Intel Mac OS X 10_13_1)AppleWebKit/537.36(KHTML,如 Gecko)Chrome/64.0 的 浏览器信息.3282.186 Safari/537.36
如果您在移动设备上执行同样的操作,您将会得到关注
Mozilla/5.0 (Linux; Android 8.1.0; Pixel Build/OPP6.171019.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36
每个移动浏览器都会有 useragent包含 "Mobile" 的字符串所以我在代码中使用上面的代码片段来检查当前是否用户代理是网络/移动的。根据结果,我将进行必要的更改。
If you goto any browser and if you try to get navigator.userAgent then we'll be getting the browser information something like following
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36
The same thing if you do in mobile you'll be getting following
Mozilla/5.0 (Linux; Android 8.1.0; Pixel Build/OPP6.171019.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36
Every mobile browser will have useragent with string containing "Mobile" So I'm using above snippet in my code to check whether current user agent is web/mobile. Based on the result I'll be doing required changes.
我用这个
I use this
mobiledetect.net 怎么样?
其他解决方案似乎太基础了。这是一个轻量级的 PHP 类。它使用 User-Agent 字符串结合特定的 HTTP 标头来检测移动环境。您还可以通过使用任何可用的第 3 方插件从 Mobile Detect 中受益:WordPress、Drupal、Joomla、Magento 等。
How about mobiledetect.net?
Other solutions seem too basic. This is a lightweight PHP class. It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment. You can also benefit from Mobile Detect by using any of the 3rd party plugins available for: WordPress, Drupal, Joomla, Magento, etc.