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

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


当前回答

对我来说,小是美丽的,所以我使用这种技巧:

在CSS文件中:

/* Smartphones ----------- */
@media only screen and (max-width: 760px) {
  #some-element { display: none; }
}

在jQuery/JavaScript文件中:

$( document ).ready(function() {      
    var is_mobile = false;

    if( $('#some-element').css('display')=='none') {
        is_mobile = true;       
    }

    // now I can use is_mobile to run javascript conditionally

    if (is_mobile == true) {
        //Conditional script here
    }
 });

我的目标是让我的网站“移动友好”。所以我使用CSS媒体查询根据屏幕大小显示/隐藏元素。

例如,在我的移动版本中,我不想激活Facebook Like Box,因为它会加载所有的个人资料图片和内容。这对移动访客来说并不好。因此,除了隐藏容器元素之外,我还在jQuery代码块(上面)中执行此操作:

if(!is_mobile) {
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/pt_PT/all.js#xfbml=1&appId=210731252294735";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
}

你可以在http://lisboaautentica.com

我仍在开发手机版,所以在写这篇文章时,它仍然看起来不像应该的样子。

由dekin88更新

有一个内置的JavaScript API用于检测媒体。不使用上述解决方案,只需使用以下方法:

$(function() {      
    let isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;

    if (isMobile) {
        //Conditional script here
    }
 });

浏览器支持:http://caniuse.com/#feat=matchmedia

这种方法的优点是,它不仅简单、更短,而且如果需要,您可以有条件地分别针对不同的设备,如智能手机和平板电脑,而无需在DOM中添加任何虚拟元素。

其他回答

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

如果要测试用户代理,正确的方法是测试用户代理(即测试navigator.userAgent)。

如果用户伪造了这一点,他们就不必担心了。如果您测试.isUnix(),则不必担心系统是否为Unix。

作为一个用户,改变userAgent也可以,但如果你这样做了,你不希望站点能够正确呈现。

如果您希望为Microsoft浏览器提供支持,则应确保内容的前几个字符包含并测试您编写的每一页。

要旨始终按照标准进行编码。然后破解它,直到它在当前版本的IE中工作&不要期望它看起来很好。GitHub就是这么做的,他们刚刚拿到了1亿美元。

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

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

看看这篇文章,它提供了一个非常好的代码片段,说明当检测到触摸设备时该怎么做,或者如果调用了touchstart事件,该怎么做:

$(function(){
  if(window.Touch) {
    touch_detect.auto_detected();
  } else {
    document.ontouchstart = touch_detect.surface;
  }
}); // End loaded jQuery
var touch_detect = {
  auto_detected: function(event){
    /* add everything you want to do onLoad here (eg. activating hover controls) */
    alert('this was auto detected');
    activateTouchArea();
  },
  surface: function(event){
    /* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
    alert('this was detected by touching');
    activateTouchArea();
  }
}; // touch_detect
function activateTouchArea(){
  /* make sure our screen doesn't scroll when we move the "touchable area" */
  var element = document.getElementById('element_id');
  element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
  /* modularize preventing the default behavior so we can use it again */
  event.preventDefault();
}

屏幕可能位于分辨率较小的桌面上,也可能位于分辨率较宽的手机上,因此,结合本问题中的两个答案

const isMobile = window.matchMedia("only screen and (max-width: 760px)");
if (/Mobi|Tablet|iPad|iPhone/i.test(navigator.userAgent) || isMobile.matches) {
    console.log('is_mobile')
}