冰豆网

分享网络精彩
bingdou.com.cn

浏览器/iframe 全屏、退出全屏

时间:2021-04-19加入收藏

外面的 html 文件 index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>fullScreen</title>
    <style>
        body {
            margin: 0;
        }
    </style>
</head>
<body>
    <iframe allowfullscreen src="iframe.html" frameborder="0" style="width: 500px;height: 500px;background:#aaa"></iframe>
</body>
</html>


里面嵌套的 iframe.html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <h1>iframe</h1>
    <button id="button">全屏</button>
    <script>
        // 判断是否允许全屏
        var fullscreenEnabled =
            document.fullscreenEnabled ||
            document.mozFullScreenEnabled ||
            document.webkitFullscreenEnabled ||
            document.msFullscreenEnabled;
        // 全屏
        function launchFullscreen(element) {
            if (element.requestFullscreen) {
                element.requestFullscreen();
            } else if (element.mozRequestFullScreen) {
                element.mozRequestFullScreen();
            } else if (element.msRequestFullscreen) {
                element.msRequestFullscreen();
            } else if (element.webkitRequestFullscreen) {
                element.webkitRequestFullScreen();
            }
        }
        // 退出全屏
        function exitFullscreen() {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            }
        }
        var btn = document.querySelector('#button');
        if (fullscreenEnabled) {
            btn.addEventListener('click', function () {
                var fullscreenElement =
                    document.fullscreenElement ||
                    document.mozFullScreenElement ||
                    document.webkitFullscreenElement;
                if (fullscreenElement) {
                    exitFullscreen();
                    btn.innerHTML = '全屏';
                } else {
                    launchFullscreen(document.documentElement);
                    btn.innerHTML = '退出全屏';
                }
            }, false);
        }
        // 监听全屏事件
        document.addEventListener('webkitfullscreenchange', function fullscreenChange() {
            if (document.fullscreenEnabled ||
                document.webkitIsFullScreen ||
                document.mozFullScreen ||
                document.msFullscreenElement) {
                console.log('enter fullscreen');
            } else {
                console.log('exit fullscreen');
            }
        }, false);
    </script>
</body>
</html>

打 赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

TGA: 技巧

分享到:


官方微信二维码冰豆网官方微信公众号