检测设备是否能够在 JavaScript 中改变方向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13803838/
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
Detecting if a device is able to change orientation in JavaScript
提问by Shadi Almosri
Is there a native JavaScript (or through the use of a library such as JQuery/Modernizr etc) way to detect if a device is capable of changing orientation? I would like to use that as a method to differentiate between desktop and mobile.
是否有原生 JavaScript(或通过使用 JQuery/Modernizr 等库)的方式来检测设备是否能够改变方向?我想用它作为区分桌面和移动设备的方法。
Thanks,
谢谢,
Shadi
沙迪
回答by Matt Coughlin
Detecting mobile devices:
检测移动设备:
Simple browser sniffing
if (/mobile/i.test(navigator.userAgent)) {...}jQuery.browser.mobileplug-in (exhaustive browser sniffing)
Simple test for touch events
if ('ontouchstart' in window) {...}Advanced test for touch events:
if (('ontouchstart' in window) || // Advanced test for touch events (window.DocumentTouch && document instanceof DocumentTouch) || ((hash['touch'] && hash['touch'].offsetTop) === 9)) {...}
简单的浏览器嗅探
if (/mobile/i.test(navigator.userAgent)) {...}jQuery.browser.mobile插件(穷尽浏览器嗅探)
触摸事件的简单测试
if ('ontouchstart' in window) {...}触摸事件的高级测试:
if (('ontouchstart' in window) || // Advanced test for touch events (window.DocumentTouch && document instanceof DocumentTouch) || ((hash['touch'] && hash['touch'].offsetTop) === 9)) {...}
Optionally use onorientationchangefor #3 and #4 above.
可选地onorientationchange用于上面的#3 和#4。
Combine 1 or more of these (and any other approaches) as needed. None of them are foolproof.
根据需要组合其中一个或多个(以及任何其他方法)。它们都不是万无一失的。

