在项目中出现了一个需求,需要实现将页面投屏到屏幕上,并能够进行开启全屏和退出全屏的操作。
尽管网上有许多第三方开源库可供使用,但由于后续业务场景的不确定性,修改源代码可能带来较大的成本和风险。鉴于全屏功能的实现并不复杂,因此我自己封装了一个解决方案。
现在,我将这个自封装的代码分享给大家,可以直接拷贝并使用。
<div id="root" style="width: 200px;height: 200px;background-color: gray;">
全屏操作
<button id="openScreen">开启全屏</button>
<button id="closeScreen">退出全屏</button>
</div>
function ScreenFull(id) {
this.status = false;
this.el = document.getElementById(id);
}
ScreenFull.prototype.open = function(cb) {
this.status = false;
this.fullScreen();
cb(this.status)
}
ScreenFull.prototype.close = function(cb) {
var _this = this;
_this.status = true;
_this.fullScreen();
cb(this.status)
}
ScreenFull.prototype.fullScreen = function() {
if (this.status) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitCancelFullScreen) { //Chrome等
document.webkitCancelFullScreen();
} else if (document.mozCancelFullScreen) { //FireFox
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) { // IE11
document.msExitFullscreen();
}
} else {
if (this.el.requestFullscreen) {
this.el.requestFullscreen();
} else if (this.el.webkitRequestFullScreen) { //Chrome等
this.el.webkitRequestFullScreen();
} else if (this.el.mozRequestFullScreen) { //FireFox
this.el.mozRequestFullScreen();
} else if (this.el.msRequestFullscreen) { // IE11
this.el.msRequestFullscreen();
}
}
this.status = !this.status;
}
var screenFull = new ScreenFull("root");
var openScreen = document.getElementById("openScreen");
// 开启全屏
openScreen.addEventListener('click', function(){
screenFull.open(function(status) {
console.log('openScreen status', status)
});
})
var closeScreen = document.getElementById("closeScreen");
// 退出全屏
closeScreen.addEventListener('click', function(){
screenFull.close(function(status) {
console.log('closeScreen status', status)
});
})