最近公司要開發一個移動端的養成類網頁遊戲(就是用手點各種按鈕最後你會找到一個女朋友=。=),要求橫屏顯示,不能豎屏。
有經驗的你肯定知道,當使用者豎屏開啟時,提示說你要把手機轉過來是在是件很傻×的事情。這時如果使用者沒開啟手機裡的橫屏模式,還要逼使用者去開啟。這時候使用者早就不耐煩的把你的遊戲關掉了。
我先進行了調研,想看有沒有現成的api。參考過screen的api以及manifest方法 ,實驗結果當然是不行。
那麼現在我唯一能想到的解決辦法,就是在豎屏模式下,寫一個橫屏的p,然後把它轉過來。
好了我的測試頁面結構如下:
<body class="webpBack"> <p id="print"> <p>lol</p> </p></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這個p在豎屏模式下橫過來,橫屏狀態下不變。所以在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這個p的寬高設定下,對齊,然後旋轉。
最終效果如下:
豎屏
橫屏
最後,這麼做帶來的後果是,如果使用者手機的旋轉螢幕按鈕開著,那麼當手機橫過來之後,會造成一定的悲劇。解決辦法如下:
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);