跳到主要內容
前端開發

移動裝置螢幕旋轉判斷與鎖定

2018 年整理的移動裝置螢幕方向筆記,包含 CSS 媒體查詢、window.orientation、舊版方向鎖定 API 與 jQuery 範例。

W

這篇是 2018 年整理移動裝置螢幕方向判斷與鎖定方式時留下來的筆記。

CSS 判斷

@media screen and (orientation: portrait) {
  /* 針對縱向 CSS 撰寫樣式 */
}

@media screen and (orientation: landscape) {
  /* 針對橫向 CSS 撰寫樣式 */
}

orientationchange 事件

<body onorientationchange="updateOrientation();">
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,
);

meta 判斷

<meta name="x5-orientation" content="portrait">

API

screen.addEventListener("orientationchange", function () {
  console.log("The orientation of the screen is: " + screen.orientation);
});

screen.lockOrientation("landscape");

CSS 強制旋轉

transform: rotate(90deg);
transform-origin: left bottom;
-ms-transform: rotate(90deg); /* Internet Explorer 9 */
-ms-transform-origin: left bottom; /* Internet Explorer 9 */
-moz-transform: rotate(90deg); /* Firefox */
-moz-transform-origin: left bottom; /* Firefox */
-webkit-transform: rotate(90deg); /* Safari & Chrome */
-webkit-transform-origin: left bottom; /* Safari & Chrome */
-o-transform: rotate(90deg); /* Opera */
-o-transform-origin: left bottom; /* Opera */

jQuery 寫法

$(document).bind("orientationchange", function () {
  if (window.orientation == 90 || window.orientation == -90) {
    $(".bottom_fix").css("position", "static");
  } else {
    $(".bottom_fix").css({
      position: "fixed",
      bottom: "0",
    });
  }
});

原文參考連結

2026 年後記

這篇保留的是 2018 年使用 window.orientationscreen.lockOrientation() 與瀏覽器專屬 meta 標籤的寫法。前兩者已經棄用或不屬於現行標準,不建議直接用在新專案。

現在若要用 JavaScript 取得或鎖定螢幕方向,可參考《screen.orientation:現在判斷與鎖定螢幕方向的做法》。其中方向鎖定仍受瀏覽器與執行情境限制;單純依橫直向調整版面時,CSS 的 orientation 媒體查詢仍然適用。

分享這篇