Javascript 检测移动设备的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3514784/
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
What is the best way to detect a mobile device?
提问by superUntitled
Is there a solid 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.
是否有可靠的方法来检测用户是否在 jQuery 中使用移动设备?类似于 CSS @media 属性的东西?如果浏览器在手持设备上,我想运行不同的脚本。
The jQuery $.browserfunction is not what I am looking for.
jQuery$.browser函数不是我要找的。
回答by sweets-BlingBling
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.
编者注:用户代理检测不是现代 Web 应用程序的推荐技术。请参阅此答案下方的评论以确认这一事实。建议使用使用特征检测和/或媒体查询的其他答案之一。
Instead of using jQuery you can use simple JavaScript to detect it:
您可以使用简单的 JavaScript 来检测它,而不是使用 jQuery:
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 // some code..
}
Or you can combine them both to make it more accessible through jQuery...
或者您可以将它们结合起来以使其更易于通过 jQuery 访问...
$.browser.device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
Now $.browserwill return "device"for all above devices
现在$.browser将返回"device"上述所有设备
Note: $.browserremoved on jQuery v1.9.1. But you can use this by using jQuery migration plugin Code
注意:$.browser在jQuery v1.9.1上删除。但是你可以通过使用jQuery迁移插件代码来使用它
A more thorough version:
更彻底的版本:
var isMobile = false; //initiate as false
// device detection
if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) 
    || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) { 
    isMobile = true;
}
回答by Gon?alo Peres
For me small is beautiful so I'm using this technique:
对我来说,小就是美,所以我正在使用这种技术:
In CSS file:
在 CSS 文件中:
/* Smartphones ----------- */
@media only screen and (max-width: 760px) {
  #some-element { display: none; }
}
In jQuery/JavaScript file:
在 jQuery/JavaScript 文件中:
$( document ).ready(function() {      
    var is_mobile = false;
    if( $('#some-element').css('display')=='none') {
        is_mobile = true;       
    }
    // now i can use is_mobile to run javascript conditionally
    if (is_mobile == true) {
        //Conditional script here
    }
 });
My objective was to have my site "mobile friendly". So I use CSS Media Queries do show/hide elements depending on the screen size.
我的目标是让我的网站“移动友好”。所以我使用 CSS Media Queries 根据屏幕大小显示/隐藏元素。
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):
例如,在我的移动版本中,我不想激活 Facebook Like Box,因为它会加载所有这些个人资料图片和内容。这对移动访问者不利。因此,除了隐藏容器元素之外,我还在 jQuery 代码块(上图)中执行此操作:
if(!is_mobile) {
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/pt_PT/all.js#xfbml=1&appId=210731252294735";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
}
You can see it in action at http://lisboaautentica.com
您可以在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
由dekin88更新
There is a JavaScript API built in for detecting media. Rather than using the above solution simply use the following:
有一个用于检测媒体的内置 JavaScript API。而不是使用上述解决方案,只需使用以下内容:
$(function() {      
    let isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;
    if (isMobile) {
        //Conditional script here
    }
 });
Browser Supports:http://caniuse.com/#feat=matchmedia
浏览器支持:http : //caniuse.com/#feat=matchmedia
The advantage to 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.
这种方法的优点是它不仅更简单、更短,而且您可以在必要时有条件地分别定位不同的设备,例如智能手机和平板电脑,而无需在 DOM 中添加任何虚拟元素。
回答by QuasarDonkey
According to Mozilla - Browser detection using the user agent:
In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device.
总之,我们建议在用户代理中的任何位置查找字符串“Mobi”以检测移动设备。
Like this:
像这样:
if (/Mobi/.test(navigator.userAgent)) {
    // mobile!
}
This will match all common mobile browser user agents, including mobile Mozilla, Safari, IE, Opera, Chrome, etc.
这将匹配所有常见的移动浏览器用户代理,包括移动 Mozilla、Safari、IE、Opera、Chrome 等。
Update for Android
安卓更新
EricL recommends testing for Androidas a user agent also, as the Chrome user agent stringfor tablets does not include "Mobi" (the phone versions do however):
EricL 也建议Android作为用户代理进行测试,因为平板电脑的Chrome 用户代理字符串不包含“Mobi”(但手机版本包含):
if (/Mobi|Android/i.test(navigator.userAgent)) {
    // mobile!
}
回答by sequielo
A simple and effective one-liner:
一个简单有效的单线:
function isMobile() { return ('ontouchstart' in document.documentElement); }
However above code doesn't take into account the case for laptops with touchscreen. Thus, I provide this second version, based on @Julian solution:
但是,上面的代码没有考虑带触摸屏的笔记本电脑的情况。因此,我提供了第二个版本,基于@Julian 解决方案:
function isMobile() {
  try{ document.createEvent("TouchEvent"); return true; }
  catch(e){ return false; }
}
回答by Bart
What you are doing by wanting to detect a mobile device is getting a little too close to a "browser sniffing" concept IMO. It would likely be much better to do some feature detection. Libraries like http://www.modernizr.com/can help with that.
您想要检测移动设备所做的事情与 IMO 的“浏览器嗅探”概念有点太接近了。做一些特征检测可能会好得多。像http://www.modernizr.com/这样的图书馆可以提供帮助。
For example, where is the line between mobile and non-mobile? It gets more and more blurry every day.
例如,移动和非移动之间的界限在哪里?一天比一天模糊。
回答by Ender
It's not jQuery, but I found this: http://detectmobilebrowser.com/
它不是 jQuery,但我发现了这个: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.
它提供脚本来检测多种语言的移动浏览器,其中一种语言是 JavaScript。这可能会帮助你找到你正在寻找的东西。
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/
但是,由于您使用的是 jQuery,您可能需要了解 jQuery.support 集合。它是用于检测当前浏览器功能的属性集合。文档在这里: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 :)
综上所述,我认为您最好的选择是使用服务器端语言重定向或编写不同的脚本到输出(如果这是一个选项)。由于您并不真正了解移动浏览器 x 的功能,因此在服务器端进行检测和更改逻辑将是最可靠的方法。当然,如果您不能使用服务器端语言,所有这些都是有争议的:)
回答by genkilabs
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.
有时需要知道客户正在使用哪个品牌的设备以显示特定于该设备的内容,例如指向 iPhone 商店或 Android 市场的链接。Modernizer 很棒,但只显示浏览器功能,如 HTML5 或 Flash。
Here is my UserAgent solution in jQuery to display a different class for each device type:
这是我在 jQuery 中的 UserAgent 解决方案,用于为每种设备类型显示不同的类:
/*** sniff the UA of the client and show hidden div's for that device ***/
var customizeForDevice = function(){
    var ua = navigator.userAgent;
    var checker = {
      iphone: ua.match(/(iPhone|iPod|iPad)/),
      blackberry: ua.match(/BlackBerry/),
      android: ua.match(/Android/)
    };
    if (checker.android){
        $('.android-only').show();
    }
    else if (checker.iphone){
        $('.idevice-only').show();
    }
    else if (checker.blackberry){
        $('.berry-only').show();
    }
    else {
        $('.unknown-device').show();
    }
}
This solution is from Graphics Maniacs http://graphicmaniacs.com/note/detecting-iphone-ipod-ipad-android-and-blackberry-browser-with-javascript-and-php/
这个解决方案来自 Graphics Maniacs http://graphicmaniacs.com/note/detecting-iphone-ipod-ipad-android-and-blackberry-browser-with-javascript-and-php/
回答by Gabriel
Found a solution in: http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/.
在以下位置找到了解决方案:http: //www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/。
var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};
And then to verify if its a Mobile, you can test using:
然后要验证它是否是移动设备,您可以使用以下方法进行测试:
if(isMobile.any()) {
   //some code...
}
回答by Chris Moschini
If by "mobile" you mean "small screen," I use this:
如果“移动”是指“小屏幕”,我使用这个:
var windowWidth = window.screen.width < window.outerWidth ?
                  window.screen.width : window.outerWidth;
var mobile = windowWidth < 500;
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.
在 iPhone 上你会得到 320 的 window.screen.width。在 Android 上你会得到 480 的 window.outerWidth(尽管这可能取决于 Android)。iPad 和 Android 平板电脑将返回 768 之类的数字,因此它们将获得您想要的完整视图。
回答by Peter-Pan
If you use Modernizr, it is very easy to use Modernizr.touchas mentioned earlier.
如果您使用Modernizr,Modernizr.touch如前所述,它非常易于使用。
However, I prefer using a combination of Modernizr.touchand user agent testing, just to be safe.
但是,Modernizr.touch为了安全起见,我更喜欢结合使用和用户代理测试。
var deviceAgent = navigator.userAgent.toLowerCase();
var isTouchDevice = Modernizr.touch || 
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/)  || 
deviceAgent.match(/(iemobile)/) || 
deviceAgent.match(/iphone/i) || 
deviceAgent.match(/ipad/i) || 
deviceAgent.match(/ipod/i) || 
deviceAgent.match(/blackberry/i) || 
deviceAgent.match(/bada/i));
if (isTouchDevice) {
        //Do something touchy
    } else {
        //Can't touch this
    }
If you don't use Modernizr, you can simply replace the Modernizr.touchfunction above with ('ontouchstart' in document.documentElement)
如果你不使用 Modernizr,你可以简单地将Modernizr.touch上面的函数替换为('ontouchstart' in document.documentElement)
Also note that testing the user agent iemobilewill give you broader range of detected Microsoft mobile devices than Windows Phone.
另请注意,iemobile与Windows Phone.

