行動裝置的使用者會隨時旋轉手機,同一個頁面可能同時要應付橫屏與豎屏兩種版面。判斷方向有 CSS 與 JS 兩條路,本文說明各自的做法與適用時機。
寫在同一份樣式表裡,用 orientation 條件分流:
@media screen and (orientation: portrait) {
/* 豎屏 css */
}
@media screen and (orientation: landscape) {
/* 橫屏 css */
}
也可以拆成兩個檔案,用 link 的 media 屬性做條件載入:
<!-- 豎屏 --> <link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css"> <!-- 橫屏 --> <link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">
拆檔的好處是橫豎其中一份樣式根本不會被下載,省一點頻寬;缺點是維護兩份檔案容易失同步。一般專案寫在同一份 CSS 裡更好管理。
// 判斷手機橫豎屏狀態
window.addEventListener(
"onorientationchange" in window ? "orientationchange" : "resize",
function () {
if (window.orientation === 180 || window.orientation === 0) {
alert('豎屏狀態!');
}
if (window.orientation === 90 || window.orientation === -90) {
alert('橫屏狀態!');
}
},
false
);
行動瀏覽器普遍支援 window.orientation 這個參數,回傳值對應如下:
90 或 -90 為橫屏,0 或 180 為豎屏0 或 180 為橫屏,90 或 -90 為豎屏注意這裡有個大坑:iOS 與 Android 的定義正好相反。這是因為 Android 的基準方向與 iOS 不同,直接寫 orientation === 0 判斷豎屏,在兩種裝置上會得到完全相反的結果。跨平台時比較穩妥的做法是比較 window.innerWidth 與 window.innerHeight:
function isLandscape() {
return window.innerWidth > window.innerHeight;
}
另外事件名稱那段 "onorientationchange" in window 的寫法值得留意:它是在偵測瀏覽器是否支援 orientationchange 事件,不支援時退回用 resize。但要注意 window.orientation 已被標為 deprecated,新專案建議直接用 matchMedia('(orientation: landscape)') 或上面的寬高比較。
單純調整樣式,用 CSS 媒體查詢就好,效能最好也不必寫 JS。需要依方向觸發程式邏輯時(例如重新初始化 canvas 尺寸、切換輪播元件、重算圖表),才需要 JS。實務上兩者常並用:CSS 負責版面,JS 負責重繪運算。
最後提醒,旋轉時若使用了固定尺寸的 canvas 或 iframe,記得在方向變化的回呼裡重新設定寬高,否則會出現變形或超出容器。