影片播放、簡報、圖表儀表板這些場景,常需要把某個區塊推到全螢幕。Full Screen API 已經是標準規格,但各家前綴與舊版 IE 的 fallback 仍需一併處理。
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<body>
<div style="margin:0 auto; height:600px; width:700px;">
<button id="btn">js 控制頁面的全屏展示和退出全屏顯示</button>
<div id="content"
style="margin:0 auto; height:500px; width:700px; background:#ccc;">
<h1>js 控制頁面的全屏展示和退出全屏顯示</h1>
</div>
</div>
<script language="JavaScript">
document.getElementById("btn").onclick = function () {
var elem = document.getElementById("content");
requestFullScreen(elem);
};
function requestFullScreen(element) {
var requestMethod =
element.requestFullScreen ||
element.webkitRequestFullScreen ||
element.mozRequestFullScreen ||
element.msRequestFullScreen;
if (requestMethod) {
requestMethod.call(element);
} else if (typeof window.ActiveXObject !== "undefined") {
// 舊版 IE 的退路:模擬按下 F11
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
</script>
</html>
requestFullScreen 是元素上的方法,呼叫後該元素會被瀏覽器提升到全螢幕,其餘內容隱藏。這裡示範把 #content 而非整個 body 送進全螢幕,這正是它的價值所在——可以只讓感興趣的區塊佔滿螢幕。
四個帶前綴的變體分別對應標準、WebKit、Mozilla 與 IE 的實作,用 || 串成責任鏈,取第一個存在的即可。requestMethod.call(element) 是必要的,因為這些方法需要正確的 this 指向。
IE 的 ActiveX + SendKeys 分支屬於完全的解法:模擬 F11 只能全螢幕整個瀏覽器視窗,無法指定元素,且需要降低安全性設定才能運作。
原範例只做了一半。使用者進入全螢幕後,雖然可以按 Esc 離開,但程式若需要主動切換,就必須實作 toggle 邏輯:
function toggleFullScreen(elem) {
var doc = document;
var fsEl = doc.fullscreenElement || doc.webkitFullscreenElement ||
doc.mozFullScreenElement || doc.msFullscreenElement;
if (!fsEl) {
var request = elem.requestFullscreen || elem.webkitRequestFullscreen ||
elem.mozRequestFullScreen || elem.msRequestFullscreen;
request && request.call(elem);
} else {
var exit = doc.exitFullscreen || doc.webkitExitFullscreen ||
doc.mozCancelFullScreen || doc.msExitFullscreen;
exit && exit.call(doc);
}
}
瀏覽器要求 requestFullscreen 必須在使用者的直接互動(點擊、按鍵)中呼叫。放在 setTimeout 或 AJAX 回呼裡呼叫會被拒絕,並拋出 TypeError。這一點無法繞過。
標準版的 requestFullscreen 回傳 Promise,失敗時應該處理:
elem.requestFullscreen().catch(function (err) {
console.warn('無法進入全螢幕:', err.message);
});
使用者按 Esc 離開時程式不會收到通知,必須透過 fullscreenchange 事件更新按鈕文字與圖示:
document.addEventListener('fullscreenchange', function () {
var btn = document.getElementById('btn');
btn.textContent = document.fullscreenElement ? '離開全螢幕' : '進入全螢幕';
});
另外值得注意:全螢幕元素内的 position:fixed 元素、以及密碼管理等瀏覽器 UI 的行為各家略有差異;iOS Safari 對非 video 元素長年不支援 Full Screen API,若需相容仍得靠 CSS 偽全螢幕(把元素設為 position:fixed 鋪滿視窗)作替代。