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

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

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


当前回答

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

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

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

谢谢跳跳虎的帮助。

其他回答

我建议你去http://wurfl.io/看看

简而言之,如果你导入一个很小的JS文件:

<script type='text/javascript' src="//wurfl.io/wurfl.js"></script>

你将得到一个JSON对象,看起来像:

{
 "complete_device_name":"Google Nexus 7",
 "is_mobile":true,
 "form_factor":"Tablet"
}

(当然,这是假设你使用的是Nexus 7),你将能够做以下事情:

if(WURFL.form_factor == "Tablet"){
    //dostuff();
}

这就是你要找的。

免责声明:我为提供这项免费服务的公司工作。谢谢。

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

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

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

谢谢跳跳虎的帮助。

这是一个比匹配更有效的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;
}

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

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

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.你想做一些具体的事情,知道他们有什么设备吗?

使用公认的答案。

//true / false
function isMobile()
{
   return (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ); 
}

您还可以按照本教程来检测特定的手机。请点击这里。