JS實現(xiàn)全屏和退出全屏
網(wǎng)頁的全屏需求在視頻網(wǎng)站中特別常見,全屏的實現(xiàn)需要瀏覽器支持弛矛,目前主流的瀏覽器都支持够吩,舊版本的IE瀏覽器可能略有瑕疵,我們可以通過JS代碼控制網(wǎng)頁進入全屏和退出全屏丈氓。
requestFullScreen API
requestFullScreen是瀏覽器提供進入全屏的接口周循,不同瀏覽器命名的接口名不同,所以需要先判斷各種瀏覽器,然后執(zhí)行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
);
}
使用示例
使用示例省略了上面部分函數(shù)代碼
<!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() {
// 省略了上面的函數(shù)代碼
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>