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

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


当前回答

仅使用matchMedia的IE10+解决方案:

const isMobile = () => window.matchMedia('(max-width: 700px)').matches

isMobile()返回布尔值

其他回答

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

我用这个

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

你需要控制大小

var  is_mobile = false;
        $(window).resize(function() {

            if ($('#mobileNav').css('display') == 'block') {
                is_mobile = true;
            }

            if (is_mobile == true) {

                console.log('is_mobile')
                document.addEventListener(
                    "DOMContentLoaded", () => {
                        new Mmenu("#mainMenu", {
                            "offCanvas": {
                                "position": "right-front"
                            }
                        });
                    }
                );

            }

        }).resize();

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

看看这篇文章,它提供了一个非常好的代码片段,说明当检测到触摸设备时该怎么做,或者如果调用了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();
}