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

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


当前回答

我用这个

if(navigator.userAgent.search("mobile")>0 ){
         do something here
}

其他回答

根据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!
}
<script>
  function checkIsMobile(){
      if(navigator.userAgent.indexOf("Mobile") > 0){
        return true;
      }else{
        return false;
      }
   }
</script>

如果您转到任何浏览器,并且尝试获取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/OOP6.171019.012)AppleWebKit/537.36(KHTML,类似Gecko)Chrome/61.0.3163.98 Mobile Safari/537.36

每个移动浏览器都会有useragent,其字符串包含“mobile”,所以我在代码中使用上面的代码片段来检查当前的用户agent是否是web/mobile。根据结果,我将进行必要的更改。

我建议你结账http://wurfl.io/

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

<script type='text/javascript' src="//wurfl.io/wurfl.js"></script>

您将看到一个JSON对象,其外观如下:

{
 "complete_device_name":"Google Nexus 7",
 "is_mobile":true,
 "form_factor":"Tablet"
}

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

if(WURFL.is_mobile) {
    //dostuff();
}

这就是你要找的。

免责声明:我为提供这项免费服务的公司工作。

function isDeviceMobile(){
 var isMobile = {
  Android: function() {
      return navigator.userAgent.match(/Android/i) && navigator.userAgent.match(/mobile|Mobile/i);
  },
  BlackBerry: function() {
      return navigator.userAgent.match(/BlackBerry/i)|| navigator.userAgent.match(/BB10; Touch/);
  },
  iOS: function() {
      return navigator.userAgent.match(/iPhone|iPod/i);
  },
  Opera: function() {
      return navigator.userAgent.match(/Opera Mini/i);
  },
  Windows: function() {
      return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/webOS/i) ;
  },
  any: function() {
      return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
  }
};      
 return isMobile.any()
}

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

按平台名称筛选。

Ex:

x = $( window ).width();

platform = navigator.platform;

alert(platform);

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


} 

^^