简体   繁体   中英

Detect if browser/device supports screen rotation

Is there a way to detect if the browser/device supports screen rotation, without having to wait for the orientationchange event? I'm not trying to detect the rotation itself, only if the browser or device supports it.

I think you can detect it like so:

if( 'onorientationchange' in window) { /* supported! */ }

However, I'm not sure if some browsers will support the event even though they never fire it.

You should assume that all devices can change their orientation because you can turn any screen to the other orientation using the OS. This is unless you lock the orientation , which is not recommended in most cases.

Technically, window.orientation and window.orientationchange are deprecated. We should instead use the screen.orientation object and change event listener.

However, Safari does not yet support screen orientation. So you should have both for now:

if (screen.orientation) {
  screen.orientation.addEventListener('change', handleOrientationChange);
} else {
  window.addEventListener('orientationchange', handleOrientationChange);
}

When the device is not rotated this listener will not fire. But it could fire for any device.

For more information, see "Managing screen orientation" in MDN's docs.

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