我们如何以编程方式在javascript中进入和退出全屏模式?

时间:2014-08-03 23:53:01

标签: javascript browser fullscreen

Here's documentation on exiting fullscreen mode.

我使用了这个代码,我学会了使浏览器全屏(它可以工作),但是我试图修改它的版本以退出全屏失败。处理这些非标准API有点棘手,每个浏览器实现它有点不同。

以下是代码:

// Bring the page into full-screen mode - Works!
function requestFullScreen(element) {

    // Supports most browsers and their versions.
    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}");
        }
    }
}

// Exit fullscreen - Doesn't work!
function exitFullScreen(element){
    var requestMethod = element.exitFullscreen || 
        element.mozCancelFullScreen            || 
        element.webkitExitFullscreen           || 
        element.msExitFullscreen;
    if (requestMethod) {
        requestMethod();
    } else {
        console.log("Oops. Request method false.");
    }
}

和电话:

var $fullscreenButton = $("#fullscreen-button");
var $smallscreenButton = $("#smallscreen-button");

$fullscreenButton.on("click", function() {
    var elem = document.body;

    // Make the body go full screen.
    requestFullScreen(elem);
});

$smallscreenButton.on("click", function() {
    var elem = document.body;

    // Exit full screen.
    exitFullScreen(elem);
});

exitFullScreen函数有什么问题?我该如何解决?

编辑:

  • 我正在为此制作一个JSFiddle!
  • 通过“不工作”,我的意思是输出"Oops. Request method false."
  • 我正在使用参数exitFullScreen()
  • 调用函数document.body

的jsfiddle:

虽然全屏请求功能通常在浏览器中适用于I could not get it to work in JSFiddle,但我不确定这是因为我自己的错误,还是与JSFiddle有关。

1 个答案:

答案 0 :(得分:5)

为了进入全屏,大写有一些问题。

对于退出,您需要在document而不是body上调用它,并且您还需要正确应用它而不是调用方法的引用。

所以requestMethod.call(element);也可以退出。

http://jsfiddle.net/gaby/FGX72/show的演示版 (在最新的IE / Chrome / FireFox上测试