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

17

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

1个回答

27

有两种方法可以实现这个:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接