【问题标题】:Detecting if a device is able to change orientation in JavaScript检测设备是否能够在 JavaScript 中改变方向
【发布时间】:2012-11-28 00:53:02
【问题描述】:

是否有原生 JavaScript(或通过使用诸如 JQuery/Modernizr 等库)的方式来检测设备是否能够改变方向?我想用它作为区分桌面和移动设备的方法。

谢谢,

沙迪

【问题讨论】:

  • 大多数操作系统不支持吗?在 Windows(我猜也是其他桌面操作系统)中,您可以根据屏幕的方向更改方向。有些人以站立、纵向等方式使用他们的 16:9 屏幕。因此,不幸的是,我认为这不是区分桌面设备和移动设备的好方法。
  • @ChristoferEliasson 虽然我同意这不是区分桌面和移动设备的最佳方式,但重要的部分是检测方向变化功能......这很有趣
  • 实际上,onorientationchange 似乎可以是window 的属性(如果可用)。我的浏览器没有它,但它似乎是一个有效的事件 - stackoverflow.com/questions/5284878/…

标签: javascript jquery orientation device-orientation orientation-changes


【解决方案1】:

检测移动设备:

  1. 简单的浏览器嗅探

    if (/mobile/i.test(navigator.userAgent)) {...}
    
  2. jQuery.browser.mobile 插件(详尽的浏览器嗅探)

  3. 触摸事件的简单测试

    if ('ontouchstart' in window) {...}
    
  4. 触摸事件的高级测试:

    if (('ontouchstart' in window) ||     // Advanced test for touch events
       (window.DocumentTouch && document instanceof DocumentTouch) ||
       ((hash['touch'] && hash['touch'].offsetTop) === 9)) {...}
    

对于上面的#3 和#4,可以选择使用onorientationchange

根据需要组合其中的一种或多种(以及任何其他方法)。它们都不是万无一失的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多