简体   繁体   中英

JavaScript algorithm to determine orientation of tablet

We're building an HTML5/JavaScript app developed for tablets, and we want to lay out my screens differently in landscape versus portrait.

Originally, we were capturing orientation change notifications, and keeping track of the current orientation (generally reported as 0, 90, -90 or 180 degrees -- see this question ). Unfortunately, different devices report different orientations as "0" . That link argues that it's a bug, but there's some evidence that this is working-as-designed -- for example, this article suggests that "landscape" is the default orientation and those devices report an orientation of "0" when held in landscape mode.

We next tried to just look at the actual screen size, assuming that when width was greater than height, we were in landscape mode. But this algorithm gets confused when the on-screen keyboard is displayed -- when the keyboard is displayed, the dimensions of the visible area are returned. When the device is, strictly speaking, in portrait mode, but the portion of the screen not obscured by the keyboard is wider than it is tall.

The response to this question is quite old. Is that still the best answer? Does anyone have a good algorithm that takes the keyboard visibility into consideration?

http://jsfiddle.net/jjc39/

Try this:

<span id="orientation">orientation</span>​

$(document).ready(checkOrientation);
$(window).resize(checkOrientation);

function checkOrientation() {
    var orientation = "Portrait";
    var screenWidth = $(window).width();
    var screenHeight = $(window).height();
    if (screenWidth > screenHeight) {
        orientation = "Landscape";
    }
    $("#orientation").html(orientation);
}​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM