开发者

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 che开发者_C百科ck 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜