最近公司要開發(fā)一個移動端的養(yǎng)成類網(wǎng)頁游戲(就是用手點各種按鈕最后你會找到一個女朋友=。=),要求橫屏顯示,不能豎屏。
有經(jīng)驗的你肯定知道,當用戶豎屏打開時,提示說你要把手機轉(zhuǎn)過來是在是件很傻×的事情。這時如果用戶沒開啟手機里的橫屏模式,還要逼用戶去開啟。這時候用戶早就不耐煩的把你的游戲關掉了。
我先進行了調(diào)研,想看有沒有現(xiàn)成的api。參考過screen的api以及manifest方法 ,實驗結果當然是不行。
那么現(xiàn)在我唯一能想到的解決辦法,就是在豎屏模式下,寫一個橫屏的div,然后把它轉(zhuǎn)過來。
好了我的測試頁面結構如下:
<body class="webpBack">
<div id="print">
<p>lol</p>
</div>
</body>
很簡單對不對,最終的理想狀態(tài)是,把lol非常和諧的橫過來。
好了來看看區(qū)分橫屏豎屏的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在豎屏模式下橫過來,橫屏狀態(tài)下不變。所以在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%');
}
在這里我們先取得了屏幕內(nèi)可用區(qū)域的寬高,然后根據(jù)寬高的關系來判斷是橫屏還是豎屏。如果是豎屏,就把print這個div的寬高設置下,對齊,然后旋轉(zhuǎn)。
最終效果如下:
豎屏
橫屏
最后,這么做帶來的后果是,如果用戶手機的旋轉(zhuǎn)屏幕按鈕開著,那么當手機橫過來之后,會造成一定的悲劇。解決辦法如下:
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);
好久之前寫的文章了,沒想到每天都有人來看。。。
這個東西成品,請參見:http://www.chubao.cn/s/godness/index.html,用手機瀏覽器打開即可。