繁体   English   中英

在加载时检测手机方向

[英]Detect Phone orientation on load

这是否可以在页面加载时使用 Javascript 检查。 我知道您可以检测到方向的变化,但是是否可以立即检查手机的 state 是什么?

谢谢

您可以检查视口的宽度和高度,看看哪个更大:

var isLandscapeMode = window.innerWidth > window.innerHeight;

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

有关移动设备上视口大小的更深入讨论,请参阅http://www.quirksmode.org/mobile/viewports2.html

(更新代码)

你可以这样做...

 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
    }
}

应在页面加载或 DOM 完成时(或在页面底部)调用orientationINIT

其中 getHeight() 和 getWidth() 应该是简单的函数,它们以数字形式返回窗口的宽度/高度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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