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

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

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


当前回答

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

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

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

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

其他回答

这就是我用的。我知道userAgent嗅探是不受欢迎的,但我的需求恰好是排除的之一!

<script>
var brow = navigator.userAgent;
    if (/mobi/i.test(brow)) {
        alert('Mobile Browser');
        // Do something for mobile
    } else {
        alert('Not on Mobile');
        // Do something for non mobile
    }
</script>

UserAgent不是100%可靠的。

window.navigator.maxTouchPoints > 1;

这就够了!它排除了浏览器开发控制台中的电话模拟器。这对我来说很重要。

最好的一定是:

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是…好吧

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

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

啊,是的,这个古老的问题……

这取决于你对知识的反应。

1. 你想改变UI,让它适合不同的屏幕尺寸吗?

使用媒体查询。

2. 你想显示/隐藏东西或改变基于鼠标和触摸的功能吗?

上面的答案可以解决问题,但也可能出现用户同时拥有两个选项并切换的情况。在这种情况下,当你检测到鼠标或触摸事件时,你可以切换一些JS变量和/或向文档主体添加一个类

  window.addEventListener("mousemove", function () {
    isTouch = false;
    document.body.classList.add("canHover");
  });
  window.addEventListener("touchstart", function () {
    isTouch = true;
    document.body.classList.remove("canHover");
  });
body.canHover #aButtonOrSomething:hover {
  //css attributes
}
  document
    .getElementById("aButtonOrSomething")
    .addEventListener("mouseover", showTooltip);
  document
    .getElementById("aButtonOrSomething")
    .addEventListener("click", function () {
      if (isTouch) showTooltip();
    });

3.你想做一些具体的事情,知道他们有什么设备吗?

使用公认的答案。