行動裝置提供了兩樣東西:
window.orientation——window 上的屬性,共有四種值:0 為豎屏(portrait)、90 為向左旋轉成橫屏(landscape)、-90 為向右旋轉成橫屏、180 為上下顛倒但仍屬豎屏。
orientationchange——一個事件,裝置旋轉時觸發,作用近似 PC 上的 resize。
兩者搭配,就能取得當前方向並即時響應:
(function () { var init = function () { var updateOrientation = function () { var orientation = window.orientation; switch (orientation) { case 90: case -90: orientation = 'landscape'; break; default: orientation = 'portrait'; break; } // 例如在 html 標籤上標記狀態,再依狀態顯示不同尺寸 document.body.parentNode.setAttribute('class', orientation); }; window.addEventListener('orientationchange', updateOrientation, false); updateOrientation(); }; window.addEventListener('DOMContentLoaded', init, false); })();CSS 端可以這樣對應:
/** 豎屏:div 邊框顯示藍色 **/ .portrait body div { border: 1px solid blue; } /** 橫屏:div 邊框顯示黃色 **/ .landscape body div { border: 1px solid yellow; }不過更推薦直接用媒體查詢,不必靠 JS 幫忙加 class:
@media all and (orientation: portrait) { body div { border: 1px solid blue; } } @media all and (orientation: landscape) { body div { border: 1px solid yellow; } }若 window.orientation 或 orientationchange 不存在(通常兩者一起沒有),就得退而求其次。早期用 Chrome 的裝置模擬模式除錯時就會遇到這個情況——模擬器並未提供該屬性。
替代判斷很簡單:比較寬與高,寬小於高即為豎屏,反之為橫屏。至於監聽時機,改用最基本的 resize 事件即可:
(function () { var updateOrientation = function () { var orientation = (window.innerWidth > window.innerHeight) ? 'landscape' : 'portrait'; document.body.parentNode.setAttribute('class', orientation); }; var init = function () { updateOrientation(); // 也可以用定時輪詢:window.setInterval(updateOrientation, 5000); window.addEventListener('resize', updateOrientation, false); }; window.addEventListener('DOMContentLoaded', init, false); })();把兩條路徑合併,就得到一個兩邊都顧到的版本:
(function () { var supportOrientation = (typeof window.orientation === 'number' && typeof window.onorientationchange === 'object'); var init = function () { var htmlNode = document.body.parentNode, orientation; var updateOrientation = function () { if (supportOrientation) { orientation = window.orientation; switch (orientation) { case 90: case -90: orientation = 'landscape'; break; default: orientation = 'portrait'; break; } } else { orientation = (window.innerWidth > window.innerHeight) ? 'landscape' : 'portrait'; } htmlNode.setAttribute('class', orientation); }; if (supportOrientation) { window.addEventListener('orientationchange', updateOrientation, false); } else { window.addEventListener('resize', updateOrientation, false); } updateOrientation(); }; window.addEventListener('DOMContentLoaded', init, false); })();用 setAttribute('class', ...) 會覆蓋原本 html 上的所有 class。若頁面上已有其他 class 需要保留,應改用 classList.add() 與 classList.remove()。
另外,直接用 window.innerWidth 判斷時,要注意桌機上縮小瀏覽器視窗也會被判定為「橫屏」。若這段邏輯只在行動裝置上執行,記得先使用者代理或 matchMedia('(pointer: coarse)') 過濾一次。
最後,純 CSS 的媒體查詢已能涵蓋絕大多數排版需求,JS 方案主要用在「需要依方向執行不同邏輯」而非「只要換樣式」的場合。能交給 CSS 的,就別用 JS。
以 orientationchange 事件監聽旋轉,搭配 window.orientation 判斷方向;不支援時退回 resize 加寬高比較。理解這個「主方案加退路」的結構,比記住單一寫法更有用。