有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。

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


当前回答

这就是我所做的:

function checkMobile() {
  var os = GetOS();
  if (os == "Android OS" || os == "iOS") {
     // do what you wanna do
     return true
  }
}

并重定向我添加location.href=“mobile.website.com”然后添加此body标记

<body onload="checkMobile()"></body>

其他回答

为了增加额外的控制层,我使用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;
}

http://www.w3schools.com/jsref/prop_nav_useragent.asp

按平台名称筛选。

Ex:

x = $( window ).width();

platform = navigator.platform;

alert(platform);

if ( (platform != Ipad) || (x < 768) )  {


} 

^^

根据Mozilla浏览器使用用户代理的检测:

总之,我们建议在User Agent中的任何位置查找字符串“Mobi”以检测移动设备。

这样地:

if (/Mobi/.test(navigator.userAgent)) {
    // mobile!
}

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

Android更新

EricL还建议将Android作为用户代理进行测试,因为平板电脑的Chrome用户代理字符串不包含“Mobi”(但手机版本包含):

if (/Mobi|Android/i.test(navigator.userAgent)) {
    // mobile!
}

在一行javascript中:

var isMobile = ('ontouchstart' in document.documentElement && /mobi/i.test(navigator.userAgent));

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

EDIT:根据评论中的反馈更新正则表达式代码。使用regex/mobi/i,i不区分大小写,mobi匹配所有移动浏览器。看见https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox

结账http://detectmobilebrowsers.com/它为您提供了多种语言的移动设备检测脚本,包括

JavaScript、jQuery、PHP、JSP、Perl、Python、ASP、C#、ColdFusion等