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

Fah*_*ikh 7 javascript android jqtouch cordova

我已经看到了很多方法来检测设备的屏幕方向,包括使用检查来测试innerWidth和innerHeight,就​​像这样.

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

但是,如果我想检查屏幕方向的变化以及事件监听器怎么办?我试过这段代码,但它对我不起作用.

  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();
Run Code Online (Sandbox Code Playgroud)

它不会检测设备方向,并且监听器不会为我注册(我正在使用Chrome的设备模拟器).

Fah*_*ikh 14

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

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

screen.orientation.type 将明确告诉您方向是什么,对于听众,您可以使用以下简单的内容:

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

其次,为了与Safari等与Screen不兼容的其他浏览器兼容,本文显示您可以继续在窗口大小调整上使用innerWidth和innerHeight.

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

 window.onresize = function(){ getOrientation(); }
Run Code Online (Sandbox Code Playgroud)

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