什么是 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); 復制代碼
小結
透過本文,其實要使用這個 API 並不困難,並且在某些場景下,我們還能直接通過 lock
方法改變屏幕的旋轉方向,提升瀏覽體驗。並且移動端上的 Chrome 和 FIrefox 支持得很好,可以考慮在你的下一個項目中使用。
文章來源: