移动端横竖屏检测

一、HTML方法检测

在html中分别引用横屏和竖屏样式

<!-- 引用竖屏的CSS文件 portrait.css -->
  <link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css" rel="external nofollow">
  
  <!-- 引用横屏的CSS文件 landscape.css -->
  <link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css" rel="external nofollow">

二、CSS方法检测

css中通过媒体查询方法来判断是横屏还是竖屏

    /* 竖屏 */
    @media screen and (orientation:portrait) {
      /* 这里写竖屏样式 */
    }

    /* 横屏 */
    @media screen and (orientation:landscape) {
      /* 这里写横屏样式 */
    }

三、JS方法检测

【1】orientationChange事件

苹果公司为移动 Safari中添加了 orientationchange 事件,orientationchange 事件在设备的纵横方向改变时触发

    window.addEventListener("orientationchange",function(){
        alert(window.orientation);
    });  

【2】orientation属性

window.orientation 获取手机的横竖的状态,window.orientation 属性中有 4个值:0和180的时候为竖屏(180为倒过来的竖屏),90和-90时为横屏(-90为倒过来的横屏)

0 表示肖像模式,90 表示向左旋转的横向模式(“主屏幕”按钮在右侧),-90 表示向右旋转的横向模 式(“主屏幕”按钮在左侧),180 表示 iPhone头朝下;但这种模式至今 尚未得到支持。如图展示了 window.orientation 的每个值的含义。

【3】案例

检测用户当前手机横竖屏状态,如果处于横屏状态,提示用户 “为了更好的观看体验,请在竖屏下浏览”,否则不提示

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    #box {
      position: fixed;
      box-sizing: border-box;
      padding: 50px;
      display: none;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, .5);
    }

    #box span {
      margin: auto;
      font: 20px/40px "宋体";
      color: #fff;
      text-align: center;
    }
  </style>
</head>

<body>
  <div id="box"><span>为了更好的观看体验,请在竖屏下浏览</span></div>
  <script>
    window.addEventListener("orientationchange", toOrientation);
    function toOrientation() {
      let box = document.querySelector("#box");
      if (window.orientation == 90 || window.orientation == -90) {
        // 横屏-显示提示
        box.style.display = "flex";
      } else {
        // 横屏-隐藏提示
        box.style.display = "none";
      }
    }
  </script>
</body>

</html>

文章每周持续更新,可以微信搜索「 前端大集锦 」第一时间阅读,回复【视频】【书籍】领取200G视频资料和30本PDF书籍资料

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@Demi

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值