トップへ(mam-mam.net/)

WEBサイトでスマートフォンの画面の向きを取得

検索:

Javascriptでスマートフォンの画面の向きを取得する

画面の向きを取得するには「screen.orientation.type」を使用し、以下のいずれかの値を返します。

portrait-primary
縦向き(上部が上)
portrait-secondary
縦向き(上部が下)
landscape-primary
横向き(上部が左)
landscape-secondary
横向き(上部が右)
「screen.orientation.angle」で画面の現在の向きの角度がわかります。
画面の向きが変わると「screen.orientation.onchange」イベントが発生します。

実行例

画面の向きを変えてみてください。


ソースコード

<div id="ori"></div>

<script>
  window.addEventListener("load",function(){
    getOrientation();
    screen.orientation.onchange=function(){
      getOrientation();;
    }
  });
  function getOrientation(){
    let type=screen.orientation.type;
    let ori="";
    if(type=="portrait-primary"){
      ori="縦向き(上部が上)";
    }else if(type=="portrait-secondary"){
      ori="縦向き(上部が下)";
    }else if(type=="landscape-primary"){
      ori="横向き(上部が左)";
    }else if(type=="landscape-secondary"){
      ori="横向き(上部が右)";
    }
    document.getElementById("ori").innerHTML=
      ori+" "+screen.orientation.angle+"度<br>"+
          "<img src='./imgs/"+type+".png'>";
  }
</script>