简体   繁体   中英

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.

is there a better way to do this? Maybe with jquery (best option), if not better javascript solution?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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