5.1 API 及相關說明

JS 或 CSS 相關功能,在各家瀏覽器有沒有支援,可參考 caniuse 網站。

document.fullscreenEnabled

判斷目前瀏覽器是否有支援全螢幕模式。

若有支援,會得到 true

若沒有支援,會得到 undefined,因為不會有 fullscreenEnabled 屬性。

document.fullscreenElement

取得目前進入全螢幕模式的元素。

如果回傳的是 null,那就代表目前沒有任何元素進入全螢幕模式。

element.requestFullscreen()

element」 指的是頁面上的任何元素節點,然後透過 requestFullscreen() 方法,讓該元素進入全螢幕模式。

document.exitFullscreen()

退出全螢幕模式。

練習 1:進入/退出 全螢幕模式

先建立 html5/fullscreen 資料夾,並在該資料夾中建立 fullscreen.html 檔案。依照以下說明撰寫 JS。

  • 判斷瀏覽器是否支援全螢幕模式,在 #fullscreen_enabled 元素中,顯示「是」或「否」。

  • 按下「網頁全螢幕」按鈕,進入網頁全螢幕。

  • 按下「影片全螢幕」按鈕,video#the_video 進入全螢幕。

  • 按下「圖片全螢幕」按鈕,img#the_img 進入全螢幕。

  • 當進入全螢幕狀態時,如果再按下其中一個按鈕,要離開全螢幕模式。

檔案內容如下(僅提供 html):

<!DOCTYPE html>
<html lang="zh-Hant" id="the_html">
  <head>
    <meta charset="utf-8">
    <title>Fullscreen</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  </head>
  <body>
    <p>目前這個瀏覽器有支援全螢幕模式嗎:<span id="fullscreen_enabled"></span></p>

    <button type="button" id="btn_fullscreen_html">網頁全螢幕</button>
    <button type="button" id="btn_fullscreen_video">影片全螢幕</button>
    <button type="button" id="btn_fullscreen_img">圖片全螢幕</button>
    <hr>

    <img id="the_img" src="https://picsum.photos/id/230/300/300">

    <video controls id="the_video" style="width: 400px;">
      <source src="https://alldata.sgp1.digitaloceanspaces.com/videos/sample.mp4"></source>
    </video>
    
    <div style="height: 2000px;border: 1px solid red;">創造很長的假內容</div>

    <script>
      window.addEventListener("load", function(){

        // 寫在這

      });
    </script>
  </body>
</html>

實際瀏覽本機端網址 http://127.0.0.1:5500/fullscreen/fullscreen.html 開始撰寫看看。

結果示意:

參考作法:(註:無法在 CodePen 中使用網頁全螢幕,因為無法針對 html 標籤設定 id,所以需在實際的網頁測試)

Last updated