效果图
核心代码
function isFullScreen() {
var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
return isFull;
};
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();
}
};
function handleFullScreen(element) {
console.log(element, "element");
if (element.requestFullscreen) {
console.log(1);
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
console.log(2);
element.mozRequestFullScreen();
} else if (element.webkitRequestFullscreen) {
console.log(3);
element.webkitRequestFullscreen();
} else if (element.msRequestFullscreen) {
console.log(4);
element.msRequestFullscreen();
}
};
完整案例
<!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>点击全屏</title>
</head>
<style>
.fullBox {
width: 600px;
height: 400px;
padding: 100px;
text-align: center;
margin: 30px auto;
background-color: pink;
box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.16), 0 3px 6px 0 rgba(0, 0, 0, 0.12), 0 5px 12px 4px rgba(0, 0, 0, 0.09);
}
.btn {
font-size: 20px;
}
</style>
<body>
<div id="box" class="fullBox">
Hello World 点击我试试
<button id="btn" class="btn" onclick="handleClick(event)">进入全屏</button>
</div>
<script>
window.onresize = function () {
var isFull = isFullScreen();
const btn = document.getElementById("btn");
if (isFull === false) {
btn.innerHTML = "进入全屏";
} else {
btn.innerHTML = "退出全屏";
}
};
const handleClick = (e) => {
const el = e.target;
var isFull = isFullScreen();
if (isFull) {
el.innerHTML = "进入全屏";
exitFullscreen();
} else {
el.innerHTML = "退出全屏";
const box = document.getElementById("box");
handleFullScreen(box);
}
};
function isFullScreen() {
var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
return isFull;
};
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();
}
};
function handleFullScreen(element) {
console.log(element, "element");
if (element.requestFullscreen) {
console.log(1);
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
console.log(2);
element.mozRequestFullScreen();
} else if (element.webkitRequestFullscreen) {
console.log(3);
element.webkitRequestFullscreen();
} else if (element.msRequestFullscreen) {
console.log(4);
element.msRequestFullscreen();
}
};
</script>
</body>
</html>