螢幕方向讀取與鎖定:Screen Orientation API
Screen Orientation API 為 Web 應用提供了讀取裝置當前螢幕方向、旋轉角度、鎖定旋轉方向、獲取方向改變事件的能力。使得特定應用在螢幕方向方面增強使用者體驗,如視訊和遊戲。該標準目前處於工作組草案狀態,最近一個修改為 1 月 29 日。
瀏覽器支援情況

屬性結構
Screen Orientation API 通過在 Screen
介面上擴充套件屬性 orientation
為我們提供該 API 的所有功能:
partial interface Screen { [SameObject] readonly attribute ScreenOrientation orientation; }; 複製程式碼
ScreenOrientation 的定義如下:
[Exposed=Window] interface ScreenOrientation : EventTarget { Promise<void> lock(OrientationLockType orientation); void unlock(); readonly attribute OrientationType type; readonly attribute unsigned short angle; attribute EventHandler onchange; }; 複製程式碼
接下來我們就來解釋如何使用與讀取這些方法和屬性。
讀取螢幕方向
讀取螢幕方向主要通過 type
和 angle
兩個屬性,前者返回旋轉方向的描述,後者返回旋轉的角度
angle
angle
屬性代表了以裝置的自然位置開始,逆時針方向上所旋轉的角度。如將手機逆時針旋轉90度變為橫屏,那麼此時 angle
則返回 90 。
type
type
屬性主要通過描述來表達螢幕的旋轉方向, type
的返回值總共有四個,對應著四個不同的旋轉方向:
portrait-primary
:豎屏狀態並且旋轉角度為 0 度,也就是裝置的自然位置
portrait-secondary
:豎屏狀並且即旋轉角度為 180 度,也就是倒著拿的位置
landscape-primary
:橫屏狀態並且旋轉角度為 90 度
landscape-secondary
:橫屏狀態並且旋轉角度為 180 度
鎖定螢幕方向
出於一些安全方面的考慮,鎖定方向時必須使頁面處於全屏狀態
鎖定
鎖定螢幕通過 lock
方法,呼叫 lock
方法需要傳入鎖定的方向描述字串,隨後該方法會返回一個 Promise。
描述字串 | 功能 |
---|---|
portrait-primary | 豎屏主方向 |
portrait-secondary | 豎屏次方向 |
landscape-primary | 橫屏主方向 |
landscape-secondary | 橫屏次方向 |
portrait | 豎屏方向(primary + secondary) |
landscape | 橫屏方向(primary + secondary) |
natural | 裝置的自然方向 |
any | 鎖定四個方向,即鎖定當前螢幕方向 |
Example:
async function lockPortrait() { // 首先進入全屏模式 await document.documentElement.requestFullscreen(); // 鎖定豎屏方向 await screen.orientation .lock('portrait') .catch(e => alert(e.message)); } 複製程式碼
解鎖
解鎖不需要額外引數,只需要呼叫 unlock
即可:
function unlock() { screen.orientation.unlock(); } 複製程式碼
螢幕方向改變事件
通過為 onchange
賦值或通過 addEventListener
都可以新增事件監聽:
function rotationChange() { console.log('rotation changed to:', screen.orientation.type); } screen.orientation.addEventListener('change', rotationChange); 複製程式碼