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

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


当前回答

这是我在项目中使用的代码:

function isMobile() {
 try {
    if(/Android|webOS|iPhone|iPad|iPod|pocket|psp|kindle|avantgo|blazer|midori|Tablet|Palm|maemo|plucker|phone|BlackBerry|symbian|IEMobile|mobile|ZuneWP7|Windows Phone|Opera Mini/i.test(navigator.userAgent)) {
     return true;
    };
    return false;
 } catch(e){ console.log("Error in isMobile"); return false; }
}

其他回答

如果您使用Modernizr,那么很容易使用前面提到的Modernizr.touch。

然而,为了安全起见,我更喜欢使用Moderniz.touch和用户代理测试的组合。

var deviceAgent = navigator.userAgent.toLowerCase();

var isTouchDevice = Modernizr.touch || 
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/)  || 
deviceAgent.match(/(iemobile)/) || 
deviceAgent.match(/iphone/i) || 
deviceAgent.match(/ipad/i) || 
deviceAgent.match(/ipod/i) || 
deviceAgent.match(/blackberry/i) || 
deviceAgent.match(/bada/i));

if (isTouchDevice) {
        //Do something touchy
    } else {
        //Can't touch this
    }

如果您不使用Modernizr,您可以简单地将上面的Modernizr.touch函数替换为(document.documentElement中的“ntouchstart”)

还要注意,测试用户代理iemobile将为您提供比Windows Phone更广泛的检测到的Microsoft移动设备。

另请参阅此SO问题

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

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

detectDeviceType();

在新版本的chrome(101)解决方案中,使用navigator.platform可能无法运行谷歌支持站点,但有一种更简单的方法来检查设备是否为移动设备。

如果(navigator.userAgentData.mobile==“true”){//移动电话代码console.log('bile');}其他{//PC和笔记本电脑代码console.log(“PC”);}

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

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这样的数字,这样它们就能像你想要的那样获得完整的视图。

你需要控制大小

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