我正在寻找一个函数,返回一个布尔值,如果用户正在使用移动浏览器与否。
我知道我可以使用导航器。userAgent并使用regex编写该函数,但是用户代理对于不同的平台来说太复杂了。我怀疑匹配所有可能的设备是否容易,我认为这个问题已经解决了很多次,所以应该有某种完整的解决方案来完成这样的任务。
我正在看这个网站,但不幸的是,脚本是如此神秘,我不知道如何使用它为我的目的,这是创建一个返回true/false的函数。
我正在寻找一个函数,返回一个布尔值,如果用户正在使用移动浏览器与否。
我知道我可以使用导航器。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
谢谢跳跳虎的帮助。
其他回答
一旦元素获得焦点,就可以立即模糊它。Bootstrap-datepicker是一个非常受欢迎且维护良好的组件,在GitHub中有近10,000个星星,它使用了这种方法:
if (window.navigator.maxTouchPoints || 'ontouchstart' in document) {
this.input.blur();
}
https://github.com/uxsolutions/bootstrap-datepicker
谢谢跳跳虎的帮助。
最好的一定是:
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是…好吧
根据MDN关于使用用户代理进行浏览器检测的文章,建议尽可能避免这种方法,并建议使用其他方法,如特征检测。
然而,如果必须使用用户代理作为检测设备是否移动的手段,他们建议:
总而言之,我们建议在中的任何地方查找字符串“Mobi” 用户代理检测移动设备。
因此,这一行代码就足够了:
const isMobileDevice = window.navigator.userAgent.toLowerCase().includes("mobi");
(更新):
正如@ zenwolf在评论中建议的那样,使用正则表达式会更好:
const isMobileDevice = /Mobi/i.test(window.navigator.userAgent)
像这样的怎么样?
if(
(screen.width <= 640) ||
(window.matchMedia &&
window.matchMedia('only screen and (max-width: 640px)').matches
)
){
// Do the mobile thing
}
我还没看到有人建议:
window.navigator.connection.type
这只存在于移动设备上,不存在于桌面浏览器上。检查该属性是否存在更简单,即if(window && window。Navigator && window.navigator.connection && window.navigator.connection.type) =>那么它是移动的
注意:这是实验性的
EDIT(07.2022):该功能被认为是一个潜在的跟踪漏洞,因此将从最新版本中删除。换句话说,不要用这个!