如何使用confirm()更改为Fullscreen整个网页?

时间:2014-09-22 18:06:13

标签: javascript html firefox greasemonkey confirm

我希望在点击确认框中的“确定”后整个网页转到全屏,但只有这样才会收到错误TypeError: docelem.requestFullscreen is not a function。我尝试了所有但没有...

var conf = confirm("Fullscreen mode?");
var docelem = document.documentElement;
if (conf == true) {
    docelem.requestFullscreen();
}
else if (conf == true) {
    docelem.mozRequestFullScreen();
}
else if (conf == true) {
    docelem.webkitRequestFullScreen();
}
else if (conf == true) {
    docelem.msRequestFullscreen();
}

有些解决方案吗?或者确认()是不可能的?因为有一个按钮工作:

(function () {
    var fullscreenon = document.getElementById("fullscreenbutton");//button Id
    if (fullscreenon) {
        fullscreenon.addEventListener("click", function () {
            var docelem = document.documentElement;
            if (docelem.requestFullscreen) {
                docelem.requestFullscreen();
            }
            else if (docelem.msRequestFullscreen) {
                docelem.msRequestFullscreen();
            }
            else if (docelem.mozRequestFullScreen) {
                docelem.mozRequestFullScreen();
            }
            else if (docelem.webkitRequestFullScreen) {
                docelem.webkitRequestFullScreen();
            }
        }, false);
    }
})();

1 个答案:

答案 0 :(得分:7)

第一,您的条件在两个样本之间有所不同。正确的代码是:

var conf = confirm("Fullscreen mode?");
var docelem = document.documentElement;

if (conf == true) {
    if (docelem.requestFullscreen) {
        docelem.requestFullscreen();
    }
    else if (docelem.mozRequestFullScreen) {
        docelem.mozRequestFullScreen();
    }
    else if (docelem.webkitRequestFullscreen) {
        docelem.webkitRequestFullscreen();
    }
    else if (docelem.msRequestFullscreen) {
        docelem.msRequestFullscreen();
    }
}

其次,重要的是,您无法在没有用户互动的情况下全屏显示页面。这是一项安全限制。如果您通过用户点击触发上面的代码,那么它将起作用。例如:

document.onclick = function (argument) {
    var conf = confirm("Fullscreen mode?");
    var docelem = document.documentElement;

    if (conf == true) {
        if (docelem.requestFullscreen) {
            docelem.requestFullscreen();
        }
        else if (docelem.mozRequestFullScreen) {
            docelem.mozRequestFullScreen();
        }
        else if (docelem.webkitRequestFullScreen) {
            docelem.webkitRequestFullScreen();
        }
        else if (docelem.msRequestFullscreen) {
            docelem.msRequestFullscreen();
        }
    }
}

如果您点击页面上的任意位置,将激活全屏模式。更多细节:https://stackoverflow.com/a/20533579/198062