我正在寻找一个函数,返回一个布尔值,如果用户正在使用移动浏览器与否。
我知道我可以使用导航器。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
谢谢跳跳虎的帮助。
其他回答
这是一个比匹配更有效的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;
}
这是我在任何情况下发现的最好的工作方法。
const deviceMotionAvailable = Array.isArray(navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i))
const isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/WPDesktop/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
如何使用
if( isMobile.any() ) alert('Mobile');
要查看用户是否在特定的移动设备上:
if( isMobile.iOS() ) alert('iOS');
裁判:http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript
github上的增强版:https://github.com/smali-kazmi/detect-mobile-browser
我搜索了Replit的代码(因为它在网站上到处都是错误),直到我看到:
(function (isTouchDevice) {
if (!isTouchDevice) return;
var isTouchClass = 'is-touch-device';
var docElement = document.documentElement;
docElement.className = docElement.className ? [docElement.className, isTouchClass].join(' ') : isTouchClass;
})(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);
所以我把它修改成这样:
function isTouchDevice() {
if (!(("ontouchstart" in window) || (window.DocumentTouch && document instanceof DocumentTouch))) {
return false
}
return true
}
来自不同用户代理的值:
Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36 (KHTML,像壁虎)Chrome/103.0.0.0 Safari/537.36: false Mozilla / 5.0 (Linux;Android 10;小米A2) AppleWebKit/537.36 (KHTML,像壁虎)Chrome/105.0.0.0移动Safari/537.36: true
检测手机或平板设备的一个好方法是查看浏览器是否可以创建触摸事件。
简单JavaScript代码:
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}
if (isMobile()) {
# do whatever you wanna do!
}
这对我来说效果很好,但是包含触摸屏的笔记本电脑设备可能会有一个问题。
我不确定触屏笔记本电脑是否会被视为移动设备,因为我还没有测试过。