橫屏豎屏處理

首先,橫豎屏狀態是沒法用程序控制的,可是能夠判斷進而處理:
 
使用window.orientation
原理:打開頁面是經過window.orientation判斷網頁是橫屏仍是豎屏,若是是豎屏,給整個頁面添加旋轉90°樣式。用戶看到橫屏效果後,旋轉手機會觸發window.orientationchange事件,而後將頁面旋轉回原來的0°。
 
屏幕方向對應的window.orientation值:
ipad: 90 或 -90 橫屏
ipad: 0 或180 豎屏
Andriod:0 或180 橫屏
Andriod: 90 或 -90 豎屏
 
參考連接:http://www.cnblogs.com/guangxiaoluo/p/3897366.html(html屏幕旋轉事件監聽--老駱)
具體作法:

一、使用onorientationchange事件的回調函數,來動態地爲body標籤添加一個叫orient的屬性,同時以body[orient=landspace]或body[orient=portrait]的方式在css中定義對應的樣式,這樣就能夠實如今不一樣的屏幕模式下顯示不一樣的樣式。以下代碼示例:javascript

複製代碼
<!Doctype html>  
    <html>  
        <head>  
            <meta charset="utf-8">  
            <meta id="viewport" name="viewport" content="width=device-width,initial-scale=1.0;">  
            <title>橫豎屏切換檢測</title>  
            <style type="text/css">  
                body[orient=landscape]{  
                    background-color: #ff0000;  
                }  
      
                body[orient=portrait]{  
                    background-color: #00ffff;  
                }  
            </style>  
        </head>  
        <body orient="landspace">  
            <div>  
                內容  
            </div>  
            <script type="text/javascript">  
                (function(){  
                    if(window.orient==0){  
                        document.body.setAttribute("orient","portrait");  
                    }else{  
                        document.body.setAttribute("orient","landscape");  
                    }  
                })();  
                window.onorientationchange=function(){  
                    var body=document.body;  
                    var viewport=document.getElementById("viewport");  
                    if(body.getAttribute("orient")=="landscape"){  
                        body.setAttribute("orient","portrait");  
                    }else{  
                        body.setAttribute("orient","landscape");  
                    }  
                };  
            </script>  
        </body>  
    </html>  
複製代碼
相關文章
相關標籤/搜索