2016-04-15 77 views
5

我见过很多方法来检测设备的屏幕方向,包括使用检查来测试innerWidth与innerHeight,就​​像这样。如何使用JavaScript检测设备方向?

function getOrientation(){ 
    var orientation = window.innerWidth > window.innerHeight ? "Landscape" : "Primary"; 
    return orientation; 
} 

但如果我要检查什么屏幕方向使用事件侦听器改变呢?我试过这段代码,但它对我不起作用。

function doOnOrientationChange() 
    { 
    switch(window.orientation) 
    { 
     case -90: 
     case 90: 
     alert('landscape'); 
     break; 
     default: 
     alert('portrait'); 
     break; 
    } 
    } 

    window.addEventListener('orientationchange', doOnOrientationChange); 

    // Initial execution if needed 
    doOnOrientationChange(); 

它不检测设备方向,并且侦听器没有为我注册(我正在使用Chrome的设备模拟器)。

回答

12

两种方法可以做到这一点:

首先,作为每Screen API文档,使用> =铬38,Firefox和IE 11,屏幕对象是可用于不仅查看方向,而且还注册每次设备方向发生变化时,监听器都会响应。

screen.orientation.type将明确地让你知道的取向是什么,并为听众可以用喜欢的东西很简单:

screen.orientation.onchange = function(){ 
    // logs 'portrait' or 'landscape' 
    console.log(screen.orientation.type.match(/\w+/)[0]); 
}; 

其次,与其他浏览器如Safari不与屏幕兼容的相容性, this post显示您可以在窗口大小调整时继续使用innerWidth和innerHeight。

function getOrientation(){ 
    var orientation = window.innerWidth > window.innerHeight ? "Landscape" : "Portrait"; 
    return orientation; 
} 

window.onresize = function(){ getOrientation(); } 
+0

值得注意的是,该解决方案仅适用于智能手机上的Chrome浏览器> = 39和Firefox Mobile。 OP添加了标签“ios”,Screen API不是解决方案。 – Popatop15