图像/ DIV元素切换全屏

时间:2015-01-18 16:21:06

标签: javascript jquery html

下面的代码是一个工作示例,当您单击它全屏打开网页浏览器的图像时,我不知道如何再次点击图像时使javascript切换全屏模式。

因此,第一次点击图像时脚本需要打开全屏模式,第二次点击同一图像时需要退出全屏模式。

HTML:

    <h1>Click image to toogle fullscreen mode</h1>
    <img id="logo" src="http://i.imgur.com/lPZh57Y.png" alt="logo" />

JavaScript的:

(function () {
    var viewFullScreen = document.getElementById("logo");
    if (viewFullScreen) {
       viewFullScreen.addEventListener("click", function () {
           var docElm = document.documentElement;
           if (docElm.requestFullscreen) {
               docElm.requestFullscreen();
           }
           else if (docElm.msRequestFullscreen) {
               docElm.msRequestFullscreen();
           }
           else if (docElm.mozRequestFullScreen) {
               docElm.mozRequestFullScreen();
           }
           else if (docElm.webkitRequestFullScreen) {
               docElm.webkitRequestFullScreen();
           }
       }, false);
   }

  var cancelFullScreen = document.getElementById("logoCONFLICT");
  if (cancelFullScreen) {
     cancelFullScreen.addEventListener("click", function () {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        }
        else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
        else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        }
        else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        }
     }, false);
  }   
})();

1 个答案:

答案 0 :(得分:3)

一个简单的解决方案是在您请求全屏时跟踪。退出全屏通话。并根据此值运行适当的代码。你不需要两个单独的点击监听器。只是另一个if else statement

<script>
(function () {
    var viewFullScreen = document.getElementById("logo");
    var isFullScreen;

    if(viewFullScreen) {
        viewFullScreen.addEventListener("click", function () {

                    if(!isFullScreen) {

                        var docElm = document.documentElement;
                        if(docElm.requestFullscreen) docElm.requestFullscreen();
                        else if(docElm.msRequestFullscreen) docElm.msRequestFullscreen();
                        else if(docElm.mozRequestFullScreen) docElm.mozRequestFullScreen();
                        else if(docElm.webkitRequestFullScreen) docElm.webkitRequestFullScreen();

                        isFullScreen = true;

                    } else {

                        if(document.exitFullscreen) document.exitFullscreen();
                        else if(document.msExitFullscreen) document.msExitFullscreen();
                        else if(document.mozCancelFullScreen) document.mozCancelFullScreen();
                        else if(document.webkitCancelFullScreen) document.webkitCancelFullScreen();

                        isFullScreen = false;
                    }

                }, false);
    }
})();
</script>

Haven没有对它进行过测试,但应该可行。更好的方法是最初检测全屏状态并监听更改as described here。而不是试图自己跟踪状态。

希望这有帮助!祝你好运!