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

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


当前回答

很好的回答,谢谢。支持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";
}

其他回答

如果发现仅检查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...
}

有时,为了显示特定于该设备的内容,需要知道客户使用的是哪个品牌的设备,例如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();
    }
}

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

我为.NET应用程序执行此操作。

在共享的_Layout.cshtml页面中,我添加了这个。

@{
    var isMobileDevice = HttpContext.Current.Request.Browser.IsMobileDevice;
}

<html lang="en" class="@((isMobileDevice)?"ismobiledevice":"")">

然后检查站点中的任何页面(jQuery):

<script>
var isMobile = $('html').hasClass('ismobiledevice');
</script>

仅使用matchMedia的IE10+解决方案:

const isMobile = () => window.matchMedia('(max-width: 700px)').matches

isMobile()返回布尔值

Window.matchMedia()

Window接口的matchMedia()方法返回一个新的MediaQueryList对象,然后可用于确定文档匹配媒体查询字符串,并监视文档,以检测何时匹配(或停止匹配)该媒体查询用法说明您可以使用返回的媒体查询来执行这两项操作即时和事件驱动的检查,以查看文档是否匹配媒体查询。执行一次性、即时检查以查看文档匹配媒体查询,查看匹配属性的值,如果文档满足媒体查询的要求。如果您需要了解文档是否匹配媒体查询,您可以随时查看更改要传递到对象的事件。有一个很好的例子Window.devicePixelRatio上的文章。

let mql = window.matchMedia('(max-width: 767px)');