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

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


当前回答

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

其他回答

我建议使用以下字符串组合,以检查是否使用了设备类型。

根据Mozilla文档字符串,建议使用Mobi。但是,如果只使用Mobi,一些旧的平板电脑不会返回真值,因此我们也应该使用Tablet字符串。

同样,为了安全起见,iPad和iPhone字符串也可以用来检查设备类型。

大多数新设备将仅对Mobi字符串返回true。

if (/Mobi|Tablet|iPad|iPhone/.test(navigator.userAgent)) {
    // do something
}

我知道这个问题有很多答案,但从我所看到的情况来看,没有人能以我的方式解决这个问题。

CSS使用宽度(媒体查询)来确定应用于基于宽度的web文档的样式。为什么不在JavaScript中使用宽度?

例如,在Bootstrap(Mobile First)媒体查询中,存在4个快照/断点:

超小型设备为768像素及以下。小型设备的像素范围从768到991。中等设备的范围从992到1199像素。大型设备为1200像素及以上。

我们也可以使用它来解决JavaScript问题。

首先,我们将创建一个函数,该函数获取窗口大小并返回一个值,该值允许我们查看设备正在查看我们的应用程序的大小:

var getBrowserWidth = function(){
    if(window.innerWidth < 768){
        // Extra Small Device
        return "xs";
    } else if(window.innerWidth < 991){
        // Small Device
        return "sm"
    } else if(window.innerWidth < 1199){
        // Medium Device
        return "md"
    } else {
        // Large Device
        return "lg"
    }
};

现在我们已经设置了函数,我们可以调用它并存储值:

var device = getBrowserWidth();

你的问题是

如果浏览器在手持设备上,我希望运行不同的脚本。

现在我们有了设备信息,剩下的就是if语句:

if(device === "xs"){
  // Enter your script for handheld devices here 
}

下面是CodePen的示例:http://codepen.io/jacob-king/pen/jWEeWG

根据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实现的建议(es6)

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

detectDeviceType();

如果你说的“移动”是指“小屏幕”,我用这个:

var windowWidth = window.screen.width < window.outerWidth ?
                  window.screen.width : window.outerWidth;
var mobile = windowWidth < 500;

在iPhone上,你会得到一个320的window.screen.width。在Android上,你将得到一个窗口.outerWidth为480(尽管这取决于Android)。iPad和Android平板电脑将返回768这样的数字,这样它们就能像你想要的那样获得完整的视图。