<!-- js点击按钮分别实现全屏以及退出全屏的方法 -->
<script>
//定义一个变量进行判断,默认false 非全屏状态
var exitFullscreen = false
// 全屏事件
function handleFullScreen() {
var element = document.documentElement;
if (this.fullscreen) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
} else {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.webkitRequestFullScreen) {
element.webkitRequestFullScreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.msRequestFullscreen) {
// IE11
element.msRequestFullscreen();
}
}
}
</script>
js关于网页全屏的代码准备好了,然后就是设置按钮,并把点击事件放进去:
<input type="button" onclick="handleFullScreen()" value="全屏显示ʾ" />
设置完成之后,就可以实现通过按钮控制网页全屏的效果了,但是问题相对应的又来了,全屏之后 ,如何退出全屏?
废话不多说,直接上代码:
<script>
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();
}
}
//监听window是否全屏,并进行相应的操作,支持esc键退出
window.onresize = function () {
var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen ||
document.msFullscreenElement || document.fullscreenElement
); //!document.webkitIsFullScreen都为true。因此用!!
if (isFull == false) {
$("#exitFullScreen").css("display", "none");
$("#fullScreen").css("display", "");
} else {
$("#exitFullScreen").css("display", "");
$("#fullScreen").css("display", "none");
}
}
</script>
js的代码完成了,接下来就是创建一个按钮来实现相对应的点击事件了:
<input type="button" onclick="exitFullscreen()" value="退出全屏" />
将这四者全部安排到位之后,我们在使用HTML的时候就可以分别通过全屏按钮,以及退出全屏按钮实现相对应的网页全屏以及退出全屏了,
另外,这个js脚本同意支持esc键退出全屏。