全屏自动点击按钮

时间:2019-04-03 22:44:40

标签: javascript jquery

当页面加载时,我必须通过自动单击网页上的按钮使浏览器进入全屏模式。

我有用于全屏显示的代码:

/* Get the element you want displayed in fullscreen */ 
var elem = document.documentElement;
/* Function to open fullscreen mode */
function openFullscreen() {
  if (elem.requestFullscreen) {
    elem.requestFullscreen();
  } else if (elem.mozRequestFullScreen) { /* Firefox */
    elem.mozRequestFullScreen();
  } else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
    elem.webkitRequestFullscreen();
  } else if (elem.msRequestFullscreen) { /* IE/Edge */
    elem.msRequestFullscreen();
  }
}

/* Function to close fullscreen mode */
function closeFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  }
}

// Events
var output = document.getElementById("myButton");
document.addEventListener("fullscreenchange", function() {
  output.innerHTML = "fullscreenchange event fired!";
});
document.addEventListener("mozfullscreenchange", function() {
  output.innerHTML = "mozfullscreenchange event fired!";
});
document.addEventListener("webkitfullscreenchange", function() {
  output.innerHTML = "webkitfullscreenchange event fired!";
});
document.addEventListener("msfullscreenchange", function() {
  output.innerHTML = "msfullscreenchange event fired!";
});
	<button id="myButton" onclick="openFullscreen()">Go Fullscreen</button>

2 个答案:

答案 0 :(得分:0)

requestFullscreen方法只能在响应用户交互或设备方向发生变化时调用。

请参阅文档下方的注释:https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen

该函数还返回Promise,如果请求失败,该Promise将被拒绝:

document.requestFullscreen().then(() => {
   // Fullscreen mode is active
}).catch(err => {
   alert(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
});

因此至少需要与该页面进行交互,否则,没有用户的“许可”,任何页面都可以进入全屏模式。

答案 1 :(得分:0)

您可以使用名为jQuery Fullscreen的插件,它允许您以全屏模式打开页面上的任何元素,而无需在所有现代浏览器(Firefox,Chrome,Safari,Opera)中使用Flash。如果浏览器不支持此功能,则该元素将被拉伸以填充屏幕,而无需切换到全屏。

下载插件here

此插件here的演示