如何使用JavaScript检测设备方向?

如何使用JavaScript检测设备方向?,javascript,android,cordova,jqtouch,Javascript,Android,Cordova,Jqtouch,我已经看到了很多检测设备屏幕方向的方法,包括使用检查来测试innerWidth和innerHeight,如下所示 function getOrientation(){ var orientation = window.innerWidth > window.innerHeight ? "Landscape" : "Primary"; return orientation; } 但是,如果我想用事件侦听器检查屏幕方向的变化,该怎么办?我已经尝试过这个代码,但它对我不起作用

我已经看到了很多检测设备屏幕方向的方法,包括使用检查来测试innerWidth和innerHeight,如下所示

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的设备模拟器)。

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

首先,根据文档,使用>=Chrome 38、Firefox和IE 11,screen对象不仅可以查看方向,还可以在每次设备方向改变时注册侦听器

screen.orientation.type
将明确告诉您方向是什么,对于侦听器,您可以使用一些简单的方法,如:

screen.orientation.onchange = function (){
    // logs 'portrait' or 'landscape'
    console.log(screen.orientation.type.match(/\w+/)[0]);
};
第二,为了与其他浏览器(如Safari)兼容(这些浏览器与Screen不兼容),您可以在调整窗口大小时继续使用innerWidth和innerHeight

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

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

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