简体   繁体   中英

Detect Phone orientation on load

Is this possible to check with Javascript on page load. I know you can detect a change in orientation but is it possible to check what state the phone is in straight away?

Thanks

You could check the viewport width and height and see which one is larger:

var isLandscapeMode = window.innerWidth > window.innerHeight;

if (isLandscapeMode) {
  // fit page to wide orientation here...
}

For a more in-depth discussion of viewport sizes on mobile devices, see http://www.quirksmode.org/mobile/viewports2.html

(Updated code)

You can do this...

 var currOrientation= '';
/************************
* Changes the (obj) element's class, to 
* -vrt (vertical)
* -hrz (horizontal)
* depending on its width
*************************/
var orientation = function( obj ){
    var w = getWidth(),
        h = getHeight();

    if( w <= h && currOrientation !== 'vrt' ){
        obj.className = 'vrt';
        currOrientation = 'vrt';
    }
    else if( currOrientation !== 'hrz' ) {
        obj.className = 'hrz';
        currOrientation = 'hrz';
    }
}
/************************
* Binding a repeating timer
************************/
var orientationINIT = function() {
    var content;
    if( (content = document.getElementsByTagName('body')[0]) != undefined ){
        orientation( content );

        var Orient = setInterval( function() {
            orientation( content );
        }, 500 ); //each 500ms a call for orientation change
    }
}

orientationINIT should be called on page load or DOM complete (or at the bottom of the page )

where getHeight() and getWidth() should be simple functions that return the window's width / height in number form.

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