我正在寻找一个函数,返回一个布尔值,如果用户正在使用移动浏览器与否。

我知道我可以使用导航器。userAgent并使用regex编写该函数,但是用户代理对于不同的平台来说太复杂了。我怀疑匹配所有可能的设备是否容易,我认为这个问题已经解决了很多次,所以应该有某种完整的解决方案来完成这样的任务。

我正在看这个网站,但不幸的是,脚本是如此神秘,我不知道如何使用它为我的目的,这是创建一个返回true/false的函数。


当前回答

最好的一定是:

var isMobile = (/Mobile/i.test(navigator.userAgent));

但是就像Yoav Barnea说的…

// Seem legit
var isMobile = ('DeviceOrientationEvent' in window || 'orientation' in window);
// But with my Chrome on windows, DeviceOrientationEvent == fct()
if (/Windows NT|Macintosh|Mac OS X|Linux/i.test(navigator.userAgent)) isMobile = false;
// My android have "linux" too
if (/Mobile/i.test(navigator.userAgent)) isMobile = true;

在这3个测试之后,我希望var isMobile是…好吧

其他回答

我来这里是为了寻找一种简单、干净的方法来检测“触屏设备”,我把它们归类为手机和平板电脑。在目前的答案中没有找到一个干净的选择,但确实计算出以下可能也会帮助到一些人。

var touchDevice = ('ontouchstart' in document.documentElement);

编辑:要同时支持带有触摸屏的台式机和手机,您可以使用以下方法:

var touchDevice = (navigator.maxTouchPoints || 'ontouchstart' in document.documentElement);

正如许多人所说,依赖于用户代理数据的移动目标是有问题的。这同样适用于屏幕大小的计数。

我的方法借鉴了CSS技术来确定界面是否是触摸的:

只使用javascript(所有现代浏览器都支持),媒体查询匹配可以轻松推断设备是否是移动设备。

function isMobile() {
    var match = window.matchMedia || window.msMatchMedia;
    if(match) {
        var mq = match("(pointer:coarse)");
        return mq.matches;
    }
    return false;
}

使用window.screen怎么样?宽度”?

if (window.screen.width < 800) {
// do something
}

or

if($(window).width() < 800) {
//do something
}

我想这是最好的方法,因为每天都有新的移动设备!

(虽然我认为旧的浏览器不支持它,但试试看吧:))

这是我在任何情况下发现的最好的工作方法。

const deviceMotionAvailable = Array.isArray(navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i))

有一个简单的技巧来检测它是否是一个移动设备。检查ontouchstart事件是否存在:

function isMobile()
{
    return "ontouchstart" in window;
}