admin管理员组

文章数量:1202779

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.

Thanks,

Shadi

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.

Thanks,

Shadi

Share Improve this question asked Dec 10, 2012 at 15:23 Shadi AlmosriShadi Almosri 12k16 gold badges60 silver badges80 bronze badges 3
  • 3 Doesn't most OS's support that? In Windows (other desktop OS's as well I guess) you can change orientation depending on the orientation of your screen. Some use their 16:9 screen in a standing, portrait orientation and so on. Thus, I don't think that will be a good way to differentiate between desktop and mobile, unfortunately. – Christofer Eliasson Commented Dec 10, 2012 at 15:26
  • @ChristoferEliasson While I agree it's not the best way to differentiate between desktop and mobile, the important part is detecting the orientation changing feature...which is interesting to find out – Ian Commented Dec 10, 2012 at 15:34
  • 2 Actually, it seems like onorientationchange can be a property of window if that's available. My browser doesn't have it, but it seems like a valid event - stackoverflow.com/questions/5284878/… – Ian Commented Dec 10, 2012 at 15:37
Add a comment  | 

1 Answer 1

Reset to default 19

Detecting mobile devices:

  1. Simple browser sniffing

    if (/mobile/i.test(navigator.userAgent)) {...}
    
  2. jQuery.browser.mobile plug-in (exhaustive browser sniffing)

  3. Simple test for touch events

    if ('ontouchstart' in window) {...}
    
  4. 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)) {...}
    

Optionally use onorientationchange for #3 and #4 above.

Combine 1 or more of these (and any other approaches) as needed. None of them are foolproof.

本文标签: jqueryDetecting if a device is able to change orientation in JavaScriptStack Overflow