Javascript

JS實現部分區域全螢幕即退出

JS實現部分區域全螢幕即退出

JS 實現部分區域全螢幕即退出

1. 首先找出要全螢幕區域

`var elem = document.getElementById("game");`

2. 建立全螢幕 function

// 局部全螢幕
function requestFullScreen(element) {
  var requestMethod =
    element.requestFullScreen ||
    element.webkitRequestFullScreen ||
    element.mozRequestFullScreen ||
    element.msRequestFullScreen;
  if (requestMethod) {
    requestMethod.call(element);
  } else if (typeof window.ActiveXObject !== "undefined") {
    var wscript = new ActiveXObject("WScript.Shell");
    if (wscript !== null) {
      wscript.SendKeys("{F11}");
    }
  }
}

3. 將選到 element 區塊全螢幕

`requestFullScreen(elem);`

4. 退出全螢幕函數

function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  }
}

5. 監聽按鈕事件

我是設置一個是否為全螢幕的變數去跑,這樣就只需要一個按鈕就可以解決

var btn = document.getElementById("btn"); // 尋找button id=btn的按鈕
btn.onclick = function () { // 監聽btn按鈕click事件
  var elem = document.getElementById("content"); // 要全螢幕的element id
  requestFullScreen(elem); // 全螢幕
};


var close = document.getElementById("close"); // 尋找button id=close的按鈕
close.onclick = function () { // 監聽close按鈕click事件
    exitFullscreen(); // 關閉全螢幕
};


---

// 以下由一個button完成
var fullscreen = false;
var btn = document.getElementById("btn");
var elem = document.getElementById("content");
btn.onclick = function () {
    if(fullscreen){
        exitFullscreen();
        fullscreen = false;
    }else{
      requestFullScreen(elem);
        fullscreen = true;
    }
};
comments powered by Disqus