简体   繁体   English

检测方向jQuery / JavaScript Mobile

[英]Detect orientation jquery/javascript mobile

I'm trying the following to detect orientation on a mobile device. 我正在尝试以下方法来检测移动设备上的方向。

On a windows phone it does nothing, and on android it gets caught in what seems like a loop as just alerts all the time. 在Windows Phone上它什么也没做,而在android上,它一直陷在似乎一直循环的状态,并且总是发出警报。

is there a better way to do this? 有一个更好的方法吗? Maybe with jquery (best option), if not better javascript solution? 也许与jQuery(最佳选择),如果没有更好的JavaScript解决方案?

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

window.addEventListener('orientationchange', doOnOrientationChange);

Orientation is subject to support and device type. 方向取决于支持和设备类型。

Here is a very simple crude method you could experiment with that would be widely supported: 这是一个非常简单的粗略方法,您可以尝试使用,得到广泛支持:

function doOnOrientationChange () {
  let landscape = ( document.body.clientWidth > document.body.clientHeight );

  alert( landscape ? 'landscape' : 'portrait' )
}


window.addEventListener('resize', doOnOrientationChange);

You could add an offset value to change the orientation result to your liking, for example you might want to clamp landscape view on certain screen resolutions that are more square. 您可以添加偏移值以根据自己的喜好更改方向结果,例如,您可能希望将横向视图固定在某些更方形的屏幕分辨率上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM