天天看點

手機上如何讓頁面強制橫屏

首先準備一段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請看這裡。

繼續閱讀