恢复div全屏的大小

时间:2016-05-27 07:16:43

标签: javascript jquery html css

我目前有一个按钮,然后点击它,触发浏览器全屏显示,然后它会生成一个标识为fScreen得到width:100%height:100%的div。

当我单击 Esc F11 按钮时,浏览器恢复到正常大小,但div fScreen已占据整个空间。在我的情况下,fScreen的原始大小是

width: 1100px;
height: 500px;

到目前为止我所做的是使用keydown函数将fScreen的css恢复回原始大小到目前为止这是我的代码并且它不会将其恢复到正常大小。

function mkFull() //make fullscreen
{       
        //fScreen DIV
        var elem = document.getElementById("fScreen");

        if (elem.requestFullscreen) 
        {
          elem.requestFullscreen();
        } 
        else if (elem.msRequestFullscreen) 
        {
          elem.msRequestFullscreen();
        } 
        else if (elem.mozRequestFullScreen) 
        {
          elem.mozRequestFullScreen();
        } 
        else if (elem.webkitRequestFullscreen) 
        {
          elem.webkitRequestFullscreen();
        }

        $('#fScreen').css({'width' : '100%' , 'height' : '85%'});
        isfull = 1;

}

    $(document).keydown(function(e) //when pressed esc and f11 revert back to original size
    {
        if (e.keyCode == 122 || e.keyCode == 27) 
        {   
            if(isfull == 1)
            {
                $('#fScreen').css({'width' : '100px' , 'height' : '500px'});
                isfull = 0;
            }   
        } 
    });

任何想法我做错了什么?

1 个答案:

答案 0 :(得分:1)

您可以收听fullscreenchange事件:https://developer.mozilla.org/en-US/docs/Web/Events/fullscreenchange

在处理程序中,保持屏幕状态(isFull

HTML

<button id="btn">Fullscreen</button>
<div id="fScreen">fscreen</div>

JS

    var elem = document.getElementById('fScreen');
    var isFull = false;

    function mkFull() {
        //fScreen DIV
        var elem = document.getElementById("fScreen");

        if (elem.requestFullscreen) {
            elem.requestFullscreen();
        } else if (elem.msRequestFullscreen) {
            elem.msRequestFullscreen();
        } else if (elem.mozRequestFullScreen) {
            elem.mozRequestFullScreen();
        } else if (elem.webkitRequestFullscreen) {
            elem.webkitRequestFullscreen();
        }
    }

    document.addEventListener('webkitfullscreenchange', function(e) {
        isFull = !isFull;

        if (isFull) {
            elem.style = 'width: 100%; height: 85%; background: green;';
        } else {
            elem.style = 'width: 100px; height: 500px; background: red;';
        }
    });

    document.getElementById('btn').addEventListener('click', mkFull);