手机上如何让页面强制横屏

首先准备一段html内容:

  <div id="content">
    <p>谁说html5不能横屏的。。。</p>
    <p>我就是要横屏。。。</p>
    <p>要横屏。。。</p>
    <p>横屏。。。</p>
    <p>屏。。。</p>
    <p>图片也是可以的。<img src="http://img001.photo.21cn.com/photos/album/20120904/o/6A7A403C29766CBCB38C616BDFD48486.jpg" /></p>
  </div>

其实原理很简单,只需要把内容向右旋转90度就变成了横屏啊。先把定位修改为absolute

    #content {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }

    #content p {
      margin: auto;
      margin-top: 20px;
      text-align: center;
    }
    img {
      width: 100px;
    }

其实除了position: absolute;这行代码其他都是不必要的,其他只是为了做一些居中对齐等。然后我们用js判断是竖屏(portrait)还是横屏(landscape),如果是竖屏,向右旋转90度。

  const width = document.documentElement.clientWidth;
  const height = document.documentElement.clientHeight;
  if (width < height) {
    console.log(width + " " + height);
    const contentDOM = document.getElementById('content');
    contentDOM.style.width = height + 'px';
    contentDOM.style.height = width + 'px';
    contentDOM.style.top = (height - width) / 2 + 'px';
    contentDOM.style.left = 0 - (height - width) / 2 + 'px';
    contentDOM.style.transform = 'rotate(90deg)';
  }

正确旋转

但是如果用户的屏幕旋转按钮开着,然后用户又把手机横过来,就悲剧了,如下图。 错误旋转

所以我们还需要监听屏幕变化,如果用户自己把屏幕横过来,就把之前的旋转去掉。

  const evt = "onorientationchange" in window ? "orientationchange" : "resize";
  window.addEventListener(evt, function () {
    const width = document.documentElement.clientWidth;
    const height = document.documentElement.clientHeight;
    const contentDOM = document.getElementById('content');
    alert('width: ' + width + ' height: ' + height)
    if (width > height) { // 横屏
      contentDOM.style.width = width + 'px';
      contentDOM.style.height = height + 'px';
      contentDOM.style.top = '0px';
      contentDOM.style.left = '0px';
      contentDOM.style.transform = 'none';
    }
    else { // 竖屏,这里微信应该由bug,我切换为竖屏的时候,width:375, height: 323, 导致不能旋转角度。 在safari、chrome上是正确的。
      alert('change to portrait')
      contentDOM.style.width = height + 'px';
      contentDOM.style.height = width + 'px';
      contentDOM.style.top = (height - width) / 2 + 'px';
      contentDOM.style.left = 0 - (height - width) / 2 + 'px';
      contentDOM.style.transform = 'rotate(90deg)';
    }

  }, false);

完整的Demo请看这里

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值