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

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


当前回答

Window.matchMedia()

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

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

其他回答

根据您想要检测移动设备的原因(这意味着这个建议不适合每个人的需要),您可以通过查看onmouseenter来实现区分,以单击毫秒差异,就像我在这个答案中描述的那样。

mobiledetect.net怎么样?

其他解决方案似乎过于基础。这是一个轻量级的PHP类。它使用用户代理字符串和特定的HTTP标头来检测移动环境。您还可以通过使用任何第三方插件从Mobile Detect中获益:WordPress、Drupal、Joomla、Magento等。

在以下位置找到解决方案: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());
    }
};

然后,要验证它是否是移动设备,您可以使用以下方法进行测试:

if(isMobile.any()) {
   //some code...
}

navigator.userAgentData.mobile返回[true|false]

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()
}