影片播放、簡報展示、圖表儀表板這類場景,往往需要把某個區域或整個網頁推到全螢幕。主流瀏覽器(Chrome、Firefox、Edge、360 等)都支援 Fullscreen API,寫法差異不大;IE 較舊版本則略有瑕疵,全螢幕後底部仍會留下狀態列。
關鍵在於各家瀏覽器早期使用了不同的函式名稱與前綴,因此必須逐一探測。以下範例可以直接存成 html 檔執行。
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js 全螢幕與離開全螢幕</title>
<body>
<!-- requestFullScreen(document.documentElement):整個網頁進入全螢幕
requestFullScreen(document.getElementById("video-box")):指定某個區塊全螢幕 -->
<button onclick="requestFullScreen(document.documentElement)">全螢幕顯示</button>
<button onclick="exitFull()">離開全螢幕</button>
<script type="text/javascript">
function requestFullScreen(element) {
// 依序嘗試各瀏覽器的實作名稱
var requestMethod = element.requestFullScreen || // W3C 標準
element.webkitRequestFullScreen || // Chrome / Safari
element.mozRequestFullScreen || // Firefox
element.msRequestFullScreen; // IE11
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>
</body>
</html>
function exitFull() {
var exitMethod = document.exitFullscreen || // W3C 標準
document.mozCancelFullScreen ||
document.webkitExitFullscreen ||
document.msExitFullscreen;
if (exitMethod) {
exitMethod.call(document);
} else if (typeof window.ActiveXObject !== "undefined") {
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
第一,全螢幕必須由使用者操作觸發。瀏覽器基於安全考量,不允許在頁面載入時自動進入全螢幕,因此這個函式一定要綁在 click 這類使用者手勢上,若在非同步回呼中呼叫,部分瀏覽器會直接拒絕。
第二,記得監聽 fullscreenchange(含 webkit/moz 前綴版本)來同步按鈕文字與圖示,因為使用者也可能按 Esc 離開全螢幕,你的狀態不會收到通知。
第三,現代專案已可直接使用無前綴的 requestFullscreen() 與 exitFullscreen(),上面那串前綴判斷主要是為了相容舊版 Safari 與 IE11;若不需要支援它們,程式碼可以大幅精簡。