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

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

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


当前回答

UserAgent不是100%可靠的。

window.navigator.maxTouchPoints > 1;

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

其他回答

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

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

or

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

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

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

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

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

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

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

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

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

最好的一定是:

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

这取决于用例。所有的移动设备都需要电池。如果你想要的是在不耗尽电池的情况下计算电量,使用电池状态API:

navigator.getBattery().then(battery => {
  battery.charging ? 'charging' : 'not charging';
});

如果您正在寻找的是表示的使用matchMedia,它返回一个布尔值:

if (window.matchMedia("(min-width: 400px)").matches) {
  /* the viewport is at least 400 pixels wide */
} else {
  /* the viewport is less than 400 pixels wide */
}

或者将它们结合起来,在平板设备上获得更好的用户体验。