📅  最后修改于: 2023-12-03 15:01:22.394000             🧑  作者: Mango
在 HTML 中,iframe 是一种内联框架,它允许在一个页面内嵌入另一个页面或者一个文档。使用 iframe 实现全屏可以在某些场景下非常有用,比如在项目展示中,能够更好地展示产品,或者在在线教学网站上更好地呈现教学内容。
通过调整 iframe 标签的样式属性来实现全屏的效果。下面是通过 JavaScript 和 CSS 实现 iframe 全屏的代码示例:
function toggleFullScreen(elem) {
elem = elem || document.documentElement;
if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) {
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
}
var elem = document.getElementsByTagName('iframe')[0];
elem.onclick = function() {
toggleFullScreen(elem);
};
iframe {
position: absolute;
display: block;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: none;
z-index: 9999;
}
完整代码:
<html>
<head>
<style>
iframe {
position: absolute;
display: block;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: none;
z-index: 9999;
}
</style>
</head>
<body>
<h1>iFrame 全屏</h1>
<iframe src="https://www.example.com"></iframe>
<script>
function toggleFullScreen(elem) {
elem = elem || document.documentElement;
if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) {
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
}
var elem = document.getElementsByTagName('iframe')[0];
elem.onclick = function() {
toggleFullScreen(elem);
};
</script>
</body>
</html>
效果图: