如何使用JavaScript检测设备方向

How to detect device orientation with JavaScript?

本文关键字:方向 检测设备 JavaScript 何使用      更新时间:2023-09-26

我看到了很多检测设备屏幕方向的方法,包括使用检查来测试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的设备模拟器)。

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

首先,根据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]);
};

其次,为了与Safari等与Screen不兼容的浏览器兼容,这篇文章展示了您可以在调整窗口大小时继续使用innerWidth和innerHeight。

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