JS实现全屏和退出全屏
网页的全屏需求在视频网站中特别常见,全屏的实现需要浏览器支持,目前主流的浏览器都支持,旧版本的IE浏览器可能略有瑕疵,我们可以通过JS代码控制网页进入全屏和退出全屏。
requestFullScreen API
requestFullScreen是浏览器提供进入全屏的接口,不同浏览器命名的接口名不同,所以需要先判断各种浏览器,然后执行call方法,IE浏览器特殊处理。
function fullScreen(element){
var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;
if (requestMethod) {
requestMethod.call(element);
} else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
exitFullscreen API
exitFullscreen是浏览器提供退出全屏的接口,同理也需要判断各种浏览器。
function exitFullScreen() {
var exitMethod = document.cancelFullScreen || document.webkitCancelFullScreen || document.mozCancelFullScreen || document.exitFullScreen;
if (exitMethod) {
exitMethod.call(document);
} else if (typeof window.ActiveXObject !== "undefined") {
var wscript = new ActiveXObject("WScript.Shell");
if (wscript != null) {
wscript.SendKeys("{F11}");
}
}
}
判断当前是否处于全屏
使用的时候判断当前是否全屏。
function isFullScreen(element) {
return (
element.fullscreen ||
element.mozFullScreen ||
element.webkitIsFullScreen ||
element.webkitFullScreen ||
element.msFullScreen
);
}
使用示例
使用示例省略了上面部分函数代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="box">
<button id="btn">button</button>
</div>
<script>
function myFun() {
// 省略了上面的函数代码
var box = document.getElementById('box');
var btn = document.getElementById('btn');
var isFull = isFullScreen(box);
btn.addEventListener("click", function () {
if (!isFull) {
console.log("进入全屏");
fullScreen(box);
isFull = true;
} else {
console.log("退出全屏");
exitFullScreen();
isFull = false;
}
})
}
myFun();
</script>
</body>
</html>