為了應(yīng)對移動(dòng)設(shè)備屏幕的碎片化,我們在開發(fā)Mobile Web應(yīng)用時(shí),一個(gè)最佳實(shí)踐就是采用流式布局,保證最大可能地利用有限的屏幕空間。由于屏幕存在著方向性,用戶在切換了屏幕的方向后,有些設(shè)計(jì)上或?qū)崿F(xiàn)上的問題就會(huì)凸顯——我們至少需要處理一下當(dāng)前顯示元素的寬度的適配(當(dāng)然,要做的可能不僅僅是這個(gè))。很多時(shí)候,我們需要為不同的屏幕方向來設(shè)計(jì)對應(yīng)的應(yīng)用顯示模式,這個(gè)時(shí)候,實(shí)時(shí)地獲知設(shè)備的模豎屏狀態(tài)就顯得極為重要。
window.orientation :這個(gè)屬性給出了當(dāng)前設(shè)備的屏幕方向,0表示豎屏,正負(fù)90表示橫屏(向左與向右)模式
onorientationchange : 在每次屏幕方向在橫豎屏間切換后,就會(huì)觸發(fā)這個(gè)window事件,用法與傳統(tǒng)的事件類似
1:使用onorientationchange事件的回調(diào)函數(shù),來動(dòng)態(tài)地為body標(biāo)簽添加一個(gè)叫orient的屬性,同時(shí)以body[orient=landspace]或body[orient=portrait]的方式在css中定義對應(yīng)的樣式,這樣就可以實(shí)現(xiàn)在不同的屏幕模式下顯示不同的樣式。如下代碼示例:
<!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> 內(nèi)容 </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>2: 類似的思路,不通過CSS的屬性選擇器來實(shí)現(xiàn),如下代碼的實(shí)現(xiàn)方案:
<!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"> .landscape body { background-color: #ff0000; } .portrait body { background-color: #00ffff; } </style> </head> <body orient="landspace"> <div> 內(nèi)容 </div> <script type="text/javascript"> (function(){ var init=function(){ var updateOrientation=function(){ var orientation=window.orientation; switch(orientation){ case 90: case -90: orientation="landscape"; break; default: orientation="portrait"; break; } document.body.parentNode.setAttribute("class",orientation); }; window.addEventListener("orientationchange",updateOrientation,false); updateOrientation(); }; window.addEventListener("DOMContentLoaded",init,false); })(); </script> </body> </html>
新聞熱點(diǎn)
疑難解答
圖片精選