LoginSignup
28
23

More than 5 years have passed since last update.

スマホの画面回転検知

Last updated at Posted at 2016-11-01

はじめに

スマホの横検知は今まで「できなくはないが動作が不安定」という認識でしたが、ちょうど横画面のときのアラートを実装する機会があったので、試行錯誤しました。

前提条件

  • orientationchange イベントは少なくとも最新版Chrome、iOS8 Safari、Android 4.xでは動くようである
  • resize イベントと画面の縦横比で振り分ける方法もあるが、URLバーやキーボードなどのUI要素との兼ね合いで不具合を起こす可能性がある
  • iOS版SafariはScreen Orientation APIに未対応( screen.orientationundefined ) の代わりに、 window.orientation をもつ
  • screen.orientation の値はAndroidの端末によっては異なるかも(これに対応するには別途対策が必要)

実装

以上を総合して以下のようなコードに落ち着きました。

var $rootElm = $('html');

$(window).on('orientationchange', (evt) => {
  var angle;
  angle = screen && screen.orientation && screen.orientation.angle;
  if (angle == null) {
    angle = window.orientation || 0;
  }
  if(angle % 180 !== 0) {
    $rootElm.addClass('is-rotated');
  } else {
    $rootElm.removeClass('is-rotated');
  }
}).trigger('orientationchange');

最後に

画面回転についてのAPIはまだ不安定なので、現状確実に検知する方法はありません。過信しないようにしましょう!

参考: Screen Orientation APIを試してみる - Qiita

28
23
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
23