需求
- 点击全屏按钮,让页面iframe全屏展示
- 点击退出全屏按钮,让页面iframe退出全屏
代码实现
<!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>
/**
* 进入全屏
* @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%;
}