DIV CSS 佈局教程網

JavaScript 控制網頁全螢幕顯示與退出全螢幕
編輯:關於JavaScript     

HTML5 的 Fullscreen API 讓網頁能進入真正的全螢幕模式。實作時最大的眉角在於瀏覽器前綴差異,本文示範一個能兼容各家引擎的包裝寫法。

程式碼

<!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>
</body>
</html>

要點說明

1. 必須使用者在場觸發。瀏覽器基於安全考量,只允許在使用者操作(點擊、按鍵)的呼叫堆疊中進入全螢幕。在 onload 或 setTimeout 中呼叫會被靜默忽略。

2. 可指定全螢幕的目標元素。範例把 #content 而非整個 body 送進全螢幕,這是 Fullscreen API 比舊 F11 方案強的地方——可以只讓某個區塊(例如影片播放器或圖表)填滿螢幕。

3. 退出全螢幕需要另一支 API。範例只示範了進入,實務上要補上 document.exitFullscreen()(含各家前綴)與切換用的 toggle 邏輯:

function exitFullScreen() {
  var exitMethod = document.exitFullscreen
                || document.webkitExitFullscreen
                || document.mozExitFullscreen
                || document.msExitFullscreen;
  if (exitMethod) { exitMethod.call(document); }
}

// 切換
if (document.fullscreenElement || document.webkitFullscreenElement) {
  exitFullScreen();
} else {
  requestFullScreen(document.getElementById("content"));
}

4. 監聽狀態變化。使用者按 Esc 也會退出全螢幕,UI 需要據此同步,請監聽 fullscreenchange(含前綴)事件。

5. 舊 IE 的 ActiveX 退路已無意義。WScript.Shell 的 SendKeys 在現代 IE 安全性設定下幾乎必然被阻擋,且它模擬的是 F11(瀏覽器全螢幕)而非元素級全螢幕,語意也不同。目前主流瀏覽器都已支援標準 API,這段 fallback 可以直接移除。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved