简单实现 iframe 全屏显示

需求

  • 点击全屏按钮,让页面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%;
	}
  • 7
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dadeity

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值