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

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

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


当前回答

触摸屏和方向解决方案在某些个人电脑上无法使用。

一些笔记本电脑有触摸屏,希望将来会有更多。 另外,虽然我无法亲自测试,但一些图形平板电脑可以作为屏幕使用,可以使用触摸屏。

探测方向也行不通。微软(Microsoft) Surface Books等一些个人电脑拥有可拆卸的屏幕,使其像平板电脑一样工作,包括定向支持。但它仍然是一台真正的个人电脑。

如果你必须检测和区分PC和移动,只需阅读用户代理。 我也不喜欢它,但它仍然是最好的方式。

其他回答

这是一个比匹配更有效的userAgent解决方案…

function _isMobile(){
    // if we want a more complete list use this: http://detectmobilebrowsers.com/
    // str.test() is more efficent than str.match()
    // remember str.test is case sensitive
    var isMobile = (/iphone|ipod|android|ie|blackberry|fennec/).test
         (navigator.userAgent.toLowerCase());
    return isMobile;
}
  isMobile() {
    if ('maxTouchPoints' in navigator) return navigator.maxTouchPoints > 0;

    const mQ = matchMedia?.('(pointer:coarse)');
    if (mQ?.media === '(pointer:coarse)') return !!mQ.matches;
    
    if ('orientation' in window) return true;
    
    return /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(navigator.userAgent) ||
      /\b(Android|Windows Phone|iPad|iPod)\b/i.test(navigator.userAgent);
  }

导航器。不建议使用userAgent嗅探,因为它不可靠且变化很大。正如您在这里看到的:https://developers.whatismybrowser.com/useragents/explore/导航器。userAgent字符串在同一浏览器的不同版本之间可能有很大差异。

这篇MDN文章可以支持这种说法:https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent#avoiding_user_agent_detection。

上面的答案是对著名的MDN文章中建议的移动检测解决方案的重构。它首先依赖于特性检查,然后作为导航器的最后手段进行回退。userAgent嗅探。

编码快乐!<3

如何:

if (typeof screen.orientation !== 'undefined') { ... }

...因为智能手机通常支持这个属性,而桌面浏览器不支持。在MDN中见。

编辑1:正如@Gajus指出的,窗口。Orientation现在已弃用,不应该使用。

编辑2:您可以使用实验屏幕。Orientation而不是弃用的window.orientation。在MDN中见。

编辑3:从窗口更改。朝向屏幕。朝向

这里有一个简单的解决方案,来自facebook的弹弓

const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
if (isMobile) {
  /* your code here */
}

IE10+解决方案仅使用matchMedia:

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

isMobile()返回布尔值