在jQuery中检测移动设备的最佳方法是什么?

sup*_*led 1564 javascript mobile jquery browser-detection

有没有一种可靠的方法来检测用户是否在jQuery中使用移动设备?类似于CSS @media属性的东西?如果浏览器在手持设备上,我想运行不同的脚本.

jQuery $.browser函数不是我想要的.

swe*_*ing 1943

您可以使用简单的JavaScript来检测它,而不是使用jQuery:

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 // some code..
}
Run Code Online (Sandbox Code Playgroud)

或者你可以将它们结合起来,使它更容易通过jQuery访问...

$.browser.device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
Run Code Online (Sandbox Code Playgroud)

现在$.browser将返回"device"上述所有设备

注意:$.browserjQuery v1.9.1删除.但是您可以通过使用jQuery迁移插件代码来使用它


更彻底的版本:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 用户代理嗅探是一种非常低级的检测技术,用户代理字符串是一个不断移动的目标,它们不应该单独受信任.投票给这篇文章的人应该考虑更多的研究. (421认同)
  • 如果您的用户足够狡猾,或者开发人员愚蠢到无法更改用户代理字符串,谁会关心他们...... (83认同)
  • 从用户代理中嗅探特定设备的问题之一是,您必须记住在新设备出现时更新检测.这不是一个理想的解决方案. (64认同)
  • 那么你认为移动电视如何用鼠标移动电视?移动是如何在双模式(带键盘或触摸屏)的Windows PC上运行?如果您在iPad发明之前就这样做了,那么您必须稍后将其添加到您的所有网站.接下来的操作系统出现了:Ubuntu Mobile,FirefoxOS,Tizen ......`.This.Is.A.Bad.Idea. (55认同)
  • Android上的Dolphin浏览器不会发送任何这些字符串! (11认同)
  • 使用标志'i'(忽略大小写),您不需要使用toLowerCase()函数. (6认同)
  • 用户代理嗅探不可靠且不断变化,这根本不是一个好方法.http://webaim.org/blog/user-agent-string-history/ (4认同)
  • 嗅探可能不好,但有很多场景是唯一可行的方法.就像向Android和iOs用户显示一个弹出窗口,安装移动应用程序而忽略其他不那么流行的移动操作系统. (4认同)
  • 那里缺少许多可能的用户代理字符串.HP平板电脑(HP Slate 7 | HP ElitePad 900 | hp-tablet | EliteBook.*Touch`),Microsoft Surface(`Windows NT [0-9.] +; ARM;`),PSVita(`Playstation.*(便携版) | Vita)`)从头顶调出那些.实际上有成千上万的制造商特定的,不包括字符串中的"Android"或类似的.考虑使用一个库来编译这些库,为您进行有效的测试,并让库保持最新. (4认同)
  • 我认为测试用户代理不是一个好主意 (3认同)
  • @杰克也;我看到您在多个答案中粘贴了相同的两条评论。这并没有多大帮助。请提供正确解决方案的链接。无休止地滚动答案,阅读“这是一个令人震惊的解决方案;使用特征检测”并没有那么有用。解释如何使用特征检测的答案在哪里?到底为什么这些其他答案还不够呢?他们什么时候不工作? (3认同)
  • 讨厌是一个回声,但这一点可以得到足够的重视.不要使用用户代理检测. (2认同)
  • 我的回答[这个答案](http://stackoverflow.com/a/11381730/1061967)似乎提供相同的交易,但是更加全面(只是抬头)的地狱,检测方法信用额度到http://detectmobilebrowsers.com/ (2认同)
  • 我同意马特.如果您的应用程序具有非常敏感/重要的关键任务功能,那么最好使用不同的方法,这可能涉及拥有一个完全独立的移动站点/应用程序.我认为这种做法在大多数情况下都是可以接受的.我们不再是90年代中期了...... (2认同)
  • 同意"不要做用户代理嗅探"它不可靠,更好的方法是像Modernizr这样的功能检测http://modernizr.com/ (2认同)
  • 请在 2023 年,不要尝试为手机创建单独的网站版本。相反,使用特征检测来确定输入机制和视口大小。不管怎样,用户代理嗅探是一个糟糕的解决方案,而且不是面向未来的。 (2认同)

小智 500

对我来说小小是美丽的所以我正在使用这种技术:

在CSS文件中:

/* Smartphones ----------- */
@media only screen and (max-width: 760px) {
  #some-element { display: none; }
}
Run Code Online (Sandbox Code Playgroud)

在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
    }
 });
Run Code Online (Sandbox Code Playgroud)

我的目标是让我的网站"移动友好".所以我使用CSS Media Queries根据屏幕大小显示/隐藏元素.

例如,在我的移动版本中,我不想激活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'));
}
Run Code Online (Sandbox Code Playgroud)

您可以在http://lisboaautentica.com上看到它的实际效果

我还在研究移动版本,所以它仍然没有看起来应该如此.

dekin88更新

内置了一个用于检测媒体的JavaScript API.而不是使用上述解决方案,只需使用以下内容:

$( document ).ready(function() {      
    var isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;

    if (isMobile) {
        //Conditional script here
    }
 });
Run Code Online (Sandbox Code Playgroud)

浏览器支持: http ://caniuse.com/#feat=matchmedia

这种方法的优点是它不仅更简单,而且更短,但如果需要,您可以有条件地针对不同的设备(如智能手机和平板电脑),而无需在DOM中添加任何虚拟元素.

  • 为什么不:`if(screen.width <= 480){// is mobile}` (93认同)
  • -1 [`screen.width`属性](https://developer.mozilla.org/en-US/docs/DOM/window.screen.width)是全局的.没有必要随意向DOM添加元素,并且不必要地引入CSS媒体查询.另外,如果浏览器在桌面上并且用户调整窗口大小,则不会更新`$ is_mobile`. (63认同)
  • 你刚刚重新发明了`window.matchMedia`:https://developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia (63认同)
  • @andrewrjones Retina设备加倍了`width`属性值IIRC.因此,视网膜iPhone的纵向宽度为"640",高度为"960",横向为"宽度"为"960",高度为"640". (23认同)
  • 你不需要在DOM中实际使用#some-element来实现这个目的吗? (7认同)
  • -1已经有很多移动设备已经全高清(1920x1080) (4认同)
  • 我喜欢这个(原始的,预编辑的)解决方案,"询问"css属性的一个(可能暂时创建)元素,以了解我的布局是否处于"移动模式",因为我避免冗余地编写和维护媒体查询css和javascript. (2认同)
  • @PaulIrish`window.matchMedia`在IE <10和IE Mobile中不起作用 (2认同)

Qua*_*key 223

根据Mozilla - 使用用户代理进行浏览器检测:

总之,我们建议在用户代理中的任何位置查找字符串"Mobi"以检测移动设备.

像这样:

if (/Mobi/.test(navigator.userAgent)) {
    // mobile!
}
Run Code Online (Sandbox Code Playgroud)

这将匹配所有常见的移动浏览器用户代理,包括移动Mozilla,Safari,IE,Opera,Chrome等.

Android更新

EricL建议您也Android作为用户代理进行测试,因为平板电脑的Chrome用户代理字符串不包含"Mobi"(但手机版本会这样做):

if (/Mobi|Android/i.test(navigator.userAgent)) {
    // mobile!
}
Run Code Online (Sandbox Code Playgroud)

  • 链接文章提到:_如果设备足够大以至于没有标记为"Mobi",那么您应该为桌面站点提供服务(最佳做法是支持触摸输入,因为更多台式机出现在触摸屏上). _ (13认同)
  • 谢谢你的回答!我更喜欢`/Mobi/i.test(navigator.userAgent)`,因为[test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/ test)它返回一个布尔值. (11认同)
  • DERP.谢谢.我无法编辑我以前的帖子.这里又是:```/Mobi/i.test(navigator.userAgent)|| /Android/i.test(navigator.userAgent的)``` (9认同)
  • 矛盾的是,三星Galaxy Note 8上的FireFox Mobile不会返回Mobi,测试将返回false. (5认同)
  • 这比其他建议的解决方案要好得多,它应该是公认的答案 (2认同)
  • 请在 2023 年,不要尝试为手机创建单独的网站版本。相反,使用特征检测来确定输入机制和视口大小。不管怎样,用户代理嗅探是一个糟糕的解决方案,而且不是面向未来的。 (2认同)

seq*_*elo 87

一个简单有效的单线程:

function isMobile() { return ('ontouchstart' in document.documentElement); }
Run Code Online (Sandbox Code Playgroud)

但是上面的代码没有考虑带触摸屏的笔记本电脑的情况.因此,我提供了基于@Julian解决方案的第二个版本:

function isMobile() {
  try{ document.createEvent("TouchEvent"); return true; }
  catch(e){ return false; }
}
Run Code Online (Sandbox Code Playgroud)

  • 那台带触摸屏的Windows笔记本电脑怎么样? (25认同)
  • 您提供的第二个`isMobile`函数在我的destop设备上返回`true` !! (谷歌Chrome v44.0) (9认同)
  • 这更像是一个isTouchSupported方法,而不是真正的移动检测. (8认同)
  • 并非所有手机都具有触摸屏。 (3认同)

Bar*_*art 80

想要检测移动设备,你正在做的事情有点过于接近"浏览器嗅探"概念IMO.进行一些特征检测可能要好得多.像http://www.modernizr.com/这样的图书馆可以提供帮助.

例如,移动和非移动之间的界限在哪里?它每天变得越来越模糊.

  • 例如,我的"移动""非移动"问题是我的翻转功能,我有JS设置关闭功能,只需要检测 (9认同)
  • 移动与非移动是一个非常大的区别,当您尝试为移动/桌面体验提供交互/ ui时,仅使用"特征检测"是愚蠢的.就个人而言,我希望有一种简单(可靠)的方式来获取当前浏览器运行的操作系统 (9认同)
  • 不过,如果您想提供特定于设备的可下载应用程序,它可能很有用. (4认同)
  • 仍然,用户可能希望为这些设备使用"jquery mobile",无论支持的功能如何. (3认同)
  • 这取决于具体情况,我正在寻找能够告诉我用户是否在移动设备上的东西,以便我可以禁用一些繁重的基于JavaScript的动画.UA嗅探比试图"检测"用户浏览器的JavaScript性能更合适. (3认同)

End*_*der 65

这不是jQuery,但我发现了这个:http://detectmobilebrowser.com/

它提供了以多种语言检测移动浏览器的脚本,其中一种是JavaScript.这可能会帮助你找到你想要的东西.

但是,由于您使用的是jQuery,因此您可能希望了解jQuery.support集合.它是用于检测当前浏览器功能的属性集合.文档在这里:http://api.jquery.com/jQuery.support/

由于我不知道你想要完成什么,我不知道哪一个最有用.

所有这一切,我认为最好的办法是使用服务器端语言(如果这是一个选项)将不同的脚本重定向或写入输出.由于您并不真正了解移动浏览器x的功能,因此在服务器端执行检测和更改逻辑将是最可靠的方法.当然,如果你不能使用服务器端语言,所有这一切都没有实际意义:)

  • 那里有一个jQuery版本,它工作得很好,但是对于平板电脑检测你必须添加`| android | ipad | playbook | silk`,如[about section](http://detectmobilebrowsers.com/about)中所述(它是按设计) (13认同)
  • 这不支持iPad.要支持iPad,请查找ip(hone | od)和"| ad" - 例如ip(hone | od | ad) (6认同)
  • @MilchePatern那是因为脚本有问题,使用iPad代替ipad,然后就可以了,我的三星Tab上有问题,不得不使用Android iso android :) (3认同)
  • 好吧,平板电脑不是手机.该网站被称为dectect**mobile**浏览器. (3认同)
  • 我刚试过detectmobilebrowser.com/的javascript,而且它不适用于iPad. (2认同)
  • @FelixEve平板电脑是移动设备,它不是智能手机,因此应将其检测出来。如果像我一样在JS中执行CPU密集型动画,则需要过滤掉所有移动设备,智能手机和平板电脑。 (2认同)

gen*_*abs 46

有时需要知道客户端使用哪个品牌设备才能显示特定于该设备的内容,例如指向iPhone商店或Android市场的链接.Modernizer很棒,但只显示浏览器功能,如HTML5或Flash.

这是我在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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这个解决方案来自Graphics Maniacs http://graphicmaniacs.com/note/detecting-iphone-ipod-ipad-android-and-blackberry-browser-with-javascript-and-php/


Gab*_*iel 43

在以下网址找到解决方案: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());
    }
};
Run Code Online (Sandbox Code Playgroud)

然后验证它是否为Mobile,您可以使用以下方法进行测试:

if(isMobile.any()) {
   //some code...
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ini 23

如果用"手机"你的意思是"小屏幕",我用这个:

var windowWidth = window.screen.width < window.outerWidth ?
                  window.screen.width : window.outerWidth;
var mobile = windowWidth < 500;
Run Code Online (Sandbox Code Playgroud)

在iPhone上,你最终会得到一个window.screen.width为320.在Android上,你最终会得到一个window.outerWidth为480(虽然这可能取决于Android).iPad和Android平板电脑将返回768这样的数字,这样他们就可以获得您想要的完整视图.


小智 15

如果你使用Modernizr,它很容易使用Modernizr.touch,如前所述.

但是,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
    }
Run Code Online (Sandbox Code Playgroud)

如果你不使用Modernizr,你可以简单地用Modernizr.touch上面的函数替换('ontouchstart' in document.documentElement)

另请注意,测试用户代理iemobile将为您提供比检测到的更广泛的Microsoft移动设备Windows Phone.

另见这个问题


小智 14

你不能依赖navigator.userAgent,不是每个设备都显示其真正的操作系统.例如,在我的HTC上,它取决于设置("使用移动版本"开/关).在http://my.clockodo.com上,我们只是用来screen.width检测小型设备.不幸的是,在某些Android版本中,screen.width存在一个错误.您可以将此方式与userAgent结合使用:

if(screen.width < 500 ||
 navigator.userAgent.match(/Android/i) ||
 navigator.userAgent.match(/webOS/i) ||
 navigator.userAgent.match(/iPhone/i) ||
 navigator.userAgent.match(/iPod/i)) {
alert("This is a mobile device");
}
Run Code Online (Sandbox Code Playgroud)

  • 许多手机的宽度> 1000,特别是在横向模式下 (6认同)

小智 13

我知道这个问题有很多答案,但是从我看到的,没有人能像我解决这个问题那样接近答案.

CSS使用宽度(媒体查询)来确定基于宽度应用于Web文档的样式.为什么不在JavaScript中使用宽度?

例如,在Bootstrap的(移动优先)媒体查询中,存在4个快照/中断点:

  • 超小型设备是768像素及以下.
  • 小型设备的范围从768到991像素.
  • 中型设备的范围为992到1199像素.
  • 大型设备为1200像素及以上.

我们也可以使用它来解决我们的JavaScript问题.

首先,我们将创建一个获取窗口大小的函数,并返回一个值,以便我们查看设备正在查看我们的应用程序的大小:

var getBrowserWidth = function(){
    if(window.innerWidth < 768){
        // Extra Small Device
        return "xs";
    } else if(window.innerWidth < 991){
        // Small Device
        return "sm"
    } else if(window.innerWidth < 1199){
        // Medium Device
        return "md"
    } else {
        // Large Device
        return "lg"
    }
};
Run Code Online (Sandbox Code Playgroud)

现在我们已经设置了函数,我们可以调用它来存储值:

var device = getBrowserWidth();
Run Code Online (Sandbox Code Playgroud)

你的问题是

如果浏览器在手持设备上,我想运行不同的脚本.

现在我们有了设备信息,剩下的就是if语句:

if(device === "xs"){
  // Enter your script for handheld devices here 
}
Run Code Online (Sandbox Code Playgroud)

以下是CodePen的示例:http://codepen.io/jacob-king/pen/jWEeWG

  • @JacobKing你说`小型设备的范围从768到991像素.这意味着它应该是`window.innerWidth <992`(包括991)同样的东西1199它应该<1200 (2认同)

Mak*_*zik 12

我很惊讶没有人指出一个不错的网站:http://detectmobilebrowsers.com/它已经有不同语言的现成代码用于移动检测(包括但不限于):

  • 阿帕奇
  • ASP
  • C#
  • IIS
  • JavaScript的
  • NGINX
  • PHP
  • Perl的
  • 蟒蛇
  • 轨道

如果您还需要检测平板电脑,只需查看关于部分的其他RegEx参数.

Android平板电脑,iPad,Kindle Fire和PlayBooks未被设计检测到.要添加对平板电脑的支持,请添加|android|ipad|playbook|silk到第一个正则表达式.


Jam*_*ate 12

在一行javascript中:

var isMobile = ('ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/));
Run Code Online (Sandbox Code Playgroud)

如果用户代理包含"Mobi"(根据MDN)并且ontouchstart可用,那么它很可能是移动设备.


MoD*_*FoX 11

如果您不是特别担心小型显示器,可以使用宽度/高度检测.因此,如果宽度低于一定的大小,移动站点就会被抛出.它可能不是完美的方式,但它可能是最容易检测多个设备.您可能需要为iPhone 4(大分辨率)添加特定的一个.


Ras*_*org 9

要添加额外的控制层,我使用HTML5存储来检测它是使用移动存储还是桌面存储.如果浏览器不支持存储,我有一系列移动浏览器名称,我将用户代理与阵列中的浏览器进行比较.

这很简单.这是功能:

// Used to detect whether the users browser is an mobile browser
function isMobile() {
    ///<summary>Detecting whether the browser is a mobile browser or desktop browser</summary>
    ///<returns>A boolean value indicating whether the browser is a mobile browser or not</returns>

    if (sessionStorage.desktop) // desktop storage 
        return false;
    else if (localStorage.mobile) // mobile storage
        return true;

    // alternative
    mobile = ['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile','tablet','mobi']; 
    var ua=navigator.userAgent.toLowerCase();
    for (var i in mobile) if (ua.indexOf(mobile[i]) > -1) return true;

    // nothing found.. assume desktop
    return false;
}
Run Code Online (Sandbox Code Playgroud)


nel*_*lek 9

我知道这是关于这种检测的一个非常古老的问题。

我的解决方案基于滚动条宽度(是否存在)。

// this function will check the width of scroller
// if scroller width is 0px it's mobile device

//function ismob() {
    var dv = document.getElementById('divscr');
    var sp=document.getElementById('res');
    if (dv.offsetWidth - dv.clientWidth == 10) {sp.innerHTML='Is mobile'; //return true; 
    } else {
    sp.innerHTML='It is not mobile'; //return false;
    }
//}
Run Code Online (Sandbox Code Playgroud)
<!-- put hidden div on very begining of page -->
<div id="divscr" style="position:fixed;top:0;left:0;width:50px;height:50px;overflow:hidden;overflow-y:scroll;z-index:-1;visibility:hidden;"></div>
<span id="res"></span>
Run Code Online (Sandbox Code Playgroud)

  • 绝对精彩!而且它是完全跨浏览器的。谢谢你!编辑:最好检查 `(dv.offsetWidth - dv.clientWidth) == 0` 因为如果窗口放大,滚动条会变得小于 10px,这在大多数具有高分辨率但小屏幕的现代笔记本电脑中都是这种情况(即15.6英寸屏幕上的4k分辨率) (3认同)

Saf*_*Ali 7

看看这篇文章,它提供了一个非常好的代码片段,用于检测触摸设备时的操作或调用touchstart事件时该怎么办:

$(function(){
  if(window.Touch) {
    touch_detect.auto_detected();
  } else {
    document.ontouchstart = touch_detect.surface;
  }
}); // End loaded jQuery
var touch_detect = {
  auto_detected: function(event){
    /* add everything you want to do onLoad here (eg. activating hover controls) */
    alert('this was auto detected');
    activateTouchArea();
  },
  surface: function(event){
    /* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
    alert('this was detected by touching');
    activateTouchArea();
  }
}; // touch_detect
function activateTouchArea(){
  /* make sure our screen doesn't scroll when we move the "touchable area" */
  var element = document.getElementById('element_id');
  element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
  /* modularize preventing the default behavior so we can use it again */
  event.preventDefault();
}
Run Code Online (Sandbox Code Playgroud)

  • 触摸检测让我陷入困境,因为一些新的Windows 8笔记本电脑在Chrome中检测到触摸屏,导致奇怪的结果. (3认同)

小智 7

很好的回答,谢谢。支持Windows Phone和Zune的小改进:

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/) ||
  navigator.userAgent.match(/Windows Phone/i) ||
  navigator.userAgent.match(/ZuneWP7/i)
) {
  // some code
  self.location = "top.htm";
}
Run Code Online (Sandbox Code Playgroud)

  • 由于您使用的是正则表达式,因此实际上使用它们:`if (navigator.userAgent.match(/Android|webOS|iPhone|iPad|etc/)){self.location = "top.htm"}` (3认同)

Mar*_*ark 7

如果发现仅仅检查navigator.userAgent并不总是可靠的。也可以通过检查来提高可靠性navigator.platform。对先前答案的简单修改似乎更好:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ||
   (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform))) {
    // some code...
}
Run Code Online (Sandbox Code Playgroud)

  • 不应随意在没有评论的情况下投票否决答案。充其量是不礼貌的。 (3认同)

Luc*_*ani 7

我建议你看看http://wurfl.io/

简而言之,如果您导入一个小的JavaScript文件:

<script type='text/javascript' src="//wurfl.io/wurfl.js"></script>
Run Code Online (Sandbox Code Playgroud)

您将看到一个JSON对象,如下所示:

{
 "complete_device_name":"Google Nexus 7",
 "is_mobile":true,
 "form_factor":"Tablet"
}
Run Code Online (Sandbox Code Playgroud)

(假设您正在使用Nexus 7),您将能够执行以下操作:

if(WURFL.is_mobile) {
    //dostuff();
}
Run Code Online (Sandbox Code Playgroud)

这就是你要找的东西.

免责声明:我为提供此免费服务的公司工作.


Jon*_*ill 6

这是一个函数,您可以使用它来获得关于您是否在移动浏览器上运行的真/假答案.是的,这是浏览器嗅探,但有时这正是你所需要的.

function is_mobile() {
    var agents = ['android', 'webos', 'iphone', 'ipad', 'blackberry'];
    for(i in agents) {
        if(navigator.userAgent.match('/'+agents[i]+'/i')) {
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)


jcu*_*bic 6

所有答案都使用user-agent来检测浏览器,但基于用户代理的设备检测不是很好的解决方案,更好的是检测触摸设备等功能(在新jQuery中他们删除$.browser并使用$.support).

要检测移动设备,您可以检查触摸事件:

function is_touch_device() {
  return 'ontouchstart' in window // works on most browsers 
      || 'onmsgesturechange' in window; // works on ie10
}
Run Code Online (Sandbox Code Playgroud)

摘自使用JavaScript检测"触摸屏"设备的最佳方法是什么?

  • 不幸的是,这不可靠,无论如何它在带触摸屏的台式机上都会返回"true".http://www.stucox.com/blog/you-cant-detect-a-touchscreen/ (4认同)
  • 不要忘记带有触摸屏和完整浏览器体验的笔记本电脑。:-) (2认同)

San*_*shi 6

我建议使用以下字符串组合来检查是否使用了设备类型.

根据Mozilla,Mobi建议使用文档字符串.但是,如果仅Mobi使用一些旧的平板电脑不会返回true ,因此我们也应该使用Tablet字符串.

同样,为了安全起见iPad,iPhone也可以使用字符串来检查设备类型.

大多数新设备将返回trueMobi单独的字符串.

if (/Mobi|Tablet|iPad|iPhone/.test(navigator.userAgent)) {
    // do something
}
Run Code Online (Sandbox Code Playgroud)

  • 我不得不在那里添加"android"来开发平板电脑.我将不得不调整,但我喜欢这种方法. (3认同)

Moh*_*day 6

我知道这个老问题,有很多答案,但我认为这个功能很简单,将有助于检测所有移动设备、平板电脑和计算机浏览器,它就像一个魅力。

function Device_Type() 
{
    var Return_Device; 
    if(/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile|w3c|acs\-|alav|alca|amoi|audi|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd\-|dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg\-c|lg\-d|lg\-g|lge\-|maui|maxo|midp|mits|mmef|mobi|mot\-|moto|mwbp|nec\-|newt|noki|palm|pana|pant|phil|play|port|prox|qwap|sage|sams|sany|sch\-|sec\-|send|seri|sgh\-|shar|sie\-|siem|smal|smar|sony|sph\-|symb|t\-mo|teli|tim\-|tosh|tsm\-|upg1|upsi|vk\-v|voda|wap\-|wapa|wapi|wapp|wapr|webc|winw|winw|xda|xda\-) /i.test(navigator.userAgent))
    {
        if(/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i.test(navigator.userAgent)) 
        {
            Return_Device = 'Tablet';
        }
        else
        {
            Return_Device = 'Mobile';
        }
    }
    else if(/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i.test(navigator.userAgent)) 
    {
        Return_Device = 'Tablet';
    }
    else
    {
        Return_Device = 'Desktop';
    }

    return Return_Device;
}
Run Code Online (Sandbox Code Playgroud)


vin*_*vin 6

您可以使用媒体查询来轻松处理它。

isMobile = function(){
    var isMobile = window.matchMedia("only screen and (max-width: 760px)");
    return isMobile.matches ? true : false
}
Run Code Online (Sandbox Code Playgroud)


NCo*_*der 5

用这个:

/**  * jQuery.browser.mobile (http://detectmobilebrowser.com/)  * jQuery.browser.mobile will be true if the browser is a mobile device  **/ (function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/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|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|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|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);
Run Code Online (Sandbox Code Playgroud)

然后用这个:

if(jQuery.browser.mobile)
{
   console.log('You are using a mobile device!');
}
else
{
   console.log('You are not using a mobile device!');
}
Run Code Online (Sandbox Code Playgroud)


luc*_*sls 5

基于http://detectmobilebrowser.com/的简单功能

function isMobile() {
    var a = navigator.userAgent||navigator.vendor||window.opera;
    return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|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(a)||/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(a.substr(0,4));
}
Run Code Online (Sandbox Code Playgroud)


Vis*_*h G 5

<script>
  function checkIsMobile(){
      if(navigator.userAgent.indexOf("Mobile") > 0){
        return true;
      }else{
        return false;
      }
   }
</script>
Run Code Online (Sandbox Code Playgroud)

如果您使用任何浏览器,并且尝试获取navigator.userAgent,那么我们将获得类似以下内容的浏览器信息

Mozilla / 5.0(Macintosh;英特尔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,Gecko一样)Chrome / 61.0.3163.98 Mobile Safari / 537.36

每个移动浏览器都将具有带“ Mobile”字符串的useragent,因此我在代码中使用以上代码片段检查当前用户代理是否为web / mobile。根据结果​​,我将进行必要的更改。


归档时间:

查看次数:

1452944 次

最近记录:

5 年,11 月 前