一、使用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>