移動端如何讓頁面強制橫屏
最近公司要開發一個移動端的養成類網頁游戲(就是用手點各種按鈕最后你會找到一個女朋友=。=),要求橫屏顯示,不能豎屏。
有經驗的你肯定知道,當用戶豎屏打開時,提示說你要把手機轉過來是在是件很傻×的事情。這時如果用戶沒開啟手機里的橫屏模式,還要逼用戶去開啟。這時候用戶早就不耐煩的把你的游戲關掉了。
我先進行了調研,想看有沒有現成的api。參考過screen的api以及manifest方法 ,實驗結果當然是不行。
那么現在我唯一能想到的解決辦法,就是在豎屏模式下,寫一個橫屏的div,然后把它轉過來。
好了我的測試頁面結構如下:
<body class="webpBack"> <div id="print"> <p>lol</p> </div> </body>
很簡單對不對,最終的理想狀態是,把lol非常和諧的橫過來。
好了來看看區分橫屏豎屏的css:
@media screen and (orientation: portrait) { html{ width : 100% ; height : 100% ; background-color: white ; overflow : hidden; } body{ width : 100% ; height : 100% ; background-color: red ; overflow : hidden; } #print{ position : absolute ; background-color: yellow ; } } @media screen and (orientation: landscape) { html{ width : 100% ; height : 100% ; background-color: white ; } body{ width : 100% ; height : 100% ; background-color: white ; } #print{ position : absolute ; top : 0 ; left : 0 ; width : 100% ; height : 100% ; background-color: yellow ; } } #print p{ margin: auto ; margin-top : 20px ; text-align: center; }
說白了,是要把print這個div在豎屏模式下橫過來,橫屏狀態下不變。所以在portrait下,沒定義它的寬高。會通過下面的js來補。
var width = document.documentElement.clientWidth; var height = document.documentElement.clientHeight; if( width < height ){ console.log(width + " " + height); $print = $('#print'); $print.width(height); $print.height(width); $print.css('top', (height-width)/2 ); $print.css('left', 0-(height-width)/2 ); $print.css('transform' , 'rotate(90deg)'); $print.css('transform-origin' , '50% 50%'); }
在這里我們先取得了屏幕內可用區域的寬高,然后根據寬高的關系來判斷是橫屏還是豎屏。如果是豎屏,就把print這個div的寬高設置下,對齊,然后旋轉。
最終效果如下:

豎屏

橫屏
最后,這么做帶來的后果是,如果用戶手機的旋轉屏幕按鈕開着,那么當手機橫過來之后,會造成一定的悲劇。解決辦法如下:
var evt = "onorientationchange" in window ? "orientationchange" : "resize"; window.addEventListener(evt, function() { console.log(evt); var width = document.documentElement.clientWidth; var height = document.documentElement.clientHeight; $print = $('#print'); if( width > height ){ $print.width(width); $print.height(height); $print.css('top', 0 ); $print.css('left', 0 ); $print.css('transform' , 'none'); $print.css('transform-origin' , '50% 50%'); } else{ $print.width(height); $print.height(width); $print.css('top', (height-width)/2 ); $print.css('left', 0-(height-width)/2 ); $print.css('transform' , 'rotate(90deg)'); $print.css('transform-origin' , '50% 50%'); } }, false);