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

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


当前回答

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

其他回答

这里还有一个使用纯JavaScript实现的建议(es6)

const detectDeviceType = () =>
    /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
        ? 'Mobile'
        : 'Desktop';

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

一种简单有效的内衬:

function isMobile() { return ('ontouchstart' in document.documentElement); }

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

function isMobile() {
  try{ document.createEvent("TouchEvent"); return true; }
  catch(e){ return false; }
}

这似乎是一个全面的现代解决方案:

https://github.com/matthewhudson/device.js

它可以检测多个平台,智能手机与平板电脑,以及方向。它还将类添加到BODY标记中,因此检测只发生一次,您可以通过一系列简单的jQuery hasClass函数来读取所使用的设备。

过来看。。。

[免责声明:我与写这封信的人无关。]

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