移动端横竖屏检测

2021-04-01  本文已影响0人  莫伊剑客

官方文档 MDN window.orientation

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>横竖屏检测</title>
  <style>
    .box {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.3);
      display: flex;
    }

    .box span {
      margin:auto;
      font:15px/40px "Songti SC";
      color: #fff;
    }
  </style>
</head>
<body>
<div class="box"><span>为了更好的观看体验,请在竖屏下浏览</span></div>
<script>

/*
* alert(window.orientation)
* window.orientation
* 横屏:90,-90
* 竖屏:0,180
*
* */
toOrientation()
window.addEventListener('orientationchange', toOrientation)

function toOrientation() {
  const box = document.querySelector('.box')
  if (Math.abs(window.orientation) === 90) {
    box.style.display = 'flex'
  } else {
    box.style.display = 'none'
  }
}
</script>
</body>
</html>

上一篇 下一篇

猜你喜欢

热点阅读