javascript 使用javascript检测移动设备的最简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16755655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
simplest way to detect if mobile device with javascript
提问by Irfan Mir
What is the simplest way to detect if the device is a mobile device with javascript?
用javascript检测设备是否是移动设备的最简单方法是什么?
I was thinking checking if the height is less than or equal to the iPhone's browser viewport height. Speaking of which, what is the iPhone's or a common viewport height for mobile devices?
我在想检查高度是否小于或等于 iPhone 的浏览器视口高度。说到这里,iPhone 或移动设备的常见视口高度是多少?
I was having some troubles with window.height;
in javascript as it was coming back undefined, however?
我window.height;
在 javascript中遇到了一些麻烦,因为它返回未定义,但是?
Anyone know how do best and simply detect if the browser is an mobile device with javascript?
任何人都知道如何最好地检测浏览器是否是带有 javascript 的移动设备?
回答by dchhetri
This is what I have for my hobby project:
这是我的业余爱好项目:
var Environment = {
//mobile or desktop compatible event name, to be used with '.on' function
TOUCH_DOWN_EVENT_NAME: 'mousedown touchstart',
TOUCH_UP_EVENT_NAME: 'mouseup touchend',
TOUCH_MOVE_EVENT_NAME: 'mousemove touchmove',
TOUCH_DOUBLE_TAB_EVENT_NAME: 'dblclick dbltap',
isAndroid: function() {
return navigator.userAgent.match(/Android/i);
},
isBlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
isIOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
isOpera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
isWindows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
isMobile: function() {
return (Environment.isAndroid() || Environment.isBlackBerry() || Environment.isIOS() || Environment.isOpera() || Environment.isWindows());
}
};
Your solution about using dimension is not a good solution. It relies on the actual device dimension and many other variables.
您关于使用维度的解决方案不是一个好的解决方案。它依赖于实际的设备尺寸和许多其他变量。