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

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

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


当前回答

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

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

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

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

其他回答

一旦元素获得焦点,就可以立即模糊它。Bootstrap-datepicker是一个非常受欢迎且维护良好的组件,在GitHub中有近10,000个星星,它使用了这种方法:

if (window.navigator.maxTouchPoints || 'ontouchstart' in document) {
    this.input.blur();
}

https://github.com/uxsolutions/bootstrap-datepicker

谢谢跳跳虎的帮助。

这取决于用例。所有的移动设备都需要电池。如果你想要的是在不耗尽电池的情况下计算电量,使用电池状态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 */
}

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

像这样的怎么样?

if(
    (screen.width <= 640) || 
    (window.matchMedia && 
     window.matchMedia('only screen and (max-width: 640px)').matches
    )
  ){
   // Do the mobile thing
}

返回'ontouchstart'在window && window.screen. availwidth < 768

这个怎么样,它扩展了上面的答案,但也检查了屏幕大小

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

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