退出全屏模式无法在Chrome上运行吗? [我想念的是什么?]

时间:2018-11-28 20:48:24

标签: javascript html5-fullscreen

我的屏幕上有两个按钮。每个人都会触发一段JavaScript代码以进入和退出全屏模式。

按钮1:进入全屏模式

按钮2:退出全屏模式

如果我首先单击按钮1 ,它将带我进入全屏模式,然后如果我单击按钮2 ,它将退出全屏模式。

但是,如果我使用 F11 或通过 chrome菜单进入全屏模式,则按钮2 不再起作用。

为什么会发生这种情况以及如何解决?

按钮1的代码:

goFullscreen();
function goFullscreen() {
    var el = document.documentElement,
      rfs = el.requestFullscreen
        || el.webkitRequestFullScreen
        || el.mozRequestFullScreen
        || el.msRequestFullscreen 
    ;

    rfs.call(el);
}

按钮2的代码:

document.webkitCancelFullScreen();

我也没有运气尝试过这个

document.webkitExitFullscreen();

1 个答案:

答案 0 :(得分:3)

您应该在执行之前进行验证。...

    function FullScreen(divID) {
        fnFullScreen(divID, !IsFullScreen());
    }
    function IsFullScreen() {
        return (document.fullscreenElement && document.fullscreenElement !== null) ||
                 (document.webkitFullscreenElement && document.webkitFullscreenElement !== null) ||
                 (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
                 (document.msFullscreenElement && document.msFullscreenElement !== null);
    }
    function fnFullScreen(divID, TurnOn) { 
        if (TurnOn) {
            var docElm = $('#' + divID).parent()[0];
            if (docElm.requestFullscreen) {
                docElm.requestFullscreen();
            } else if (docElm.mozRequestFullScreen) {
                docElm.mozRequestFullScreen();
            } else if (docElm.webkitRequestFullScreen) {
                docElm.webkitRequestFullScreen();
            } else if (docElm.msRequestFullscreen) {
                docElm.msRequestFullscreen();
            }
            $('#' + divID).css("min-height", "100vh");
            $('.btnFullScreen').html('Exit Full Screen');
        } else { 
            if (document.exitFullscreen) {
                document.exitFullscreen().catch(() => { });
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }
             
            $('#' + divID).css("min-height", "");
            $('.btnFullScreen').html('Full Screen');
        }
    }
 

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <div class="body">
   <div id="div1"> <button class="btnFullScreen"  onclick="FullScreen('div1')">Full Screen</button> click to full screen</div>
   </div>