简单实现 iframe 全屏显示

Updated on in 前端 with 0 views and 0 comments

需求

  • 点击全屏按钮,让页面iframe全屏展示
  • 点击退出全屏按钮,让页面iframe退出全屏

代码实现

  • HTML代码实现
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {margin: 0;padding: 0;}
        .content-parent {width: 800px;height: 600px;margin: 0 auto;background-color: aquamarine;}
        .content-parent h1 {text-align: center;}
        /*设置全屏样式*/
        #iframe-one:-webkit-full-screen {width: 100%;height: 100%;}
    </style>
</head>
<body>
<div class="content-parent">
    <button id="goAmpl">子页面全屏化</button>
    <button id="outAmpl"></button>
    <iframe id="iframe-one" name="iframe-one" src="https://www.baidu.com" width="100%" height="200" scrolling="no"
            frameborder="0"></iframe>
 
</div>
</body>
</html>
  • JavaScript 代码实现
	/**
     * 进入全屏
     * @param element
     */
    function requestFullScreen(element) {
        var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;
        if (requestMethod) {
            requestMethod.call(element);
        } else if (typeof window.ActiveXObject !== "undefined") {
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript !== null) {
                wscript.SendKeys("{F11}");
            }
        }
    }


    /**
     * 退出全屏
     */
    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();
        }
    }
  
    document.getElementById('goAmpl').onclick = function () {
        let iframe = document.getElementById("iframe-one");
        requestFullScreen(iframe);
    }
    document.getElementById('outAmpl').onclick = function () {
        let iframe = document.getElementById("iframe-one");
        exitFullscreen(iframe);
    }

注意

  • 如果div不设置background style则使用webkitRequestFullScreen全屏时,div会被黑色填充
  • WebKit 不会自动添加全屏样式,需要手动实现
	#iframe-one:-webkit-full-screen {
		width: 100%;
		height: 100%;
	}

标题:简单实现 iframe 全屏显示
作者:dduan
地址:https://dduan.site/articles/2019/12/06/1575630542343.html