How to exit fullscreen onclick using Javascript?

后端 未结 5 992
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 03:14

Not sure if the following code snip will work embedded on SO, as it didn\'t work when pasting it, however it does work stand-alone.

The problem, is I want this to be a t

5条回答
  •  一向
    一向 (楼主)
    2021-01-31 03:54

    A more generalized helper (derived from the accepted answer)...

    Get Mode

    The function can be invoked without arguments to find out if the browser is currently in Fullscreen Mode. It returns true if so and false otherwise.

    Set Mode

    The function can be invoked with a bool to explicitly set the current mode, where true ensures the browser is in Fullscreen Mode, and false ensures it isn't.

    Toggle Mode

    The function can be invoked with null as the only argument to implicitly set the mode to the opposite of whatever mode it is currently in.


    let fullscreen = function() {
    
        let enter = function() {
            let body = document.body;
            if (body.requestFullscreen) body.requestFullscreen();
            else if (body.webkitRequestFullscreen) body.webkitRequestFullscreen();
            else if (body.mozRequestFullScreen) body.mozRequestFullScreen();
            else if (body.msRequestFullscreen) body.msRequestFullscreen();
        };
    
        let exit = function() {
            if (document.exitFullscreen) document.exitFullscreen();
            else if (document.webkitExitFullscreen) document.webkitExitFullscreen();
            else if (document.mozCancelFullScreen) document.mozCancelFullScreen();
            else if (document.msExitFullscreen) document.msExitFullscreen();
        };
    
        let attemptToGetState = element => element && element !== null;
    
        return function(action=undefined) {
            if (action === true) enter();
            else if (action === false) exit();
            else {
                let currentlyFullscreen = (
                    attemptToGetState(document.fullscreenElement)       ||
                    attemptToGetState(document.webkitFullscreenElement) ||
                    attemptToGetState(document.mozFullScreenElement)    ||
                    attemptToGetState(document.msFullscreenElement)
                );
                if (action === undefined) return !! currentlyFullscreen;
                else currentlyFullscreen ? exit() : enter();
            }
        };
    
    }();
    

提交回复
热议问题