JS实现页面全屏功能

时间:2022-08-05 10:06:40
 
<div id="videobox"></div>

進入全屏事件:

 
launchFullscreen(element) {
	//此方法不可以在異步任務中執行,否則火狐無法全屏
	if(element.requestFullscreen) {
		element.requestFullscreen();
	} else if(element.mozRequestFullScreen) {
		element.mozRequestFullScreen();
	} else if(element.msRequestFullscreen) {
		element.msRequestFullscreen();
	} else if(element.oRequestFullscreen) {
		element.oRequestFullscreen();
	} else if(element.webkitRequestFullscreen) {
		element.webkitRequestFullScreen();
	} else {
		var docHtml = document.documentElement;
		var docBody = document.body;
		var videobox = document.getElementById('videobox');
		var width = window.screen.width;
		var height = window.screen.height;
		var cssText = "width:" + width + ";height:" + height + ";overflow:hidden;";
		docHtml.style.cssText = cssText;
		docBody.style.cssText = cssText;
		document.IsFullScreen = true;
	}
}


退出全屏:
 
exitFullscreen() {
	if(document.exitFullscreen) {
		document.exitFullscreen();
	} else if(document.msExitFullscreen) {
		document.msExitFullscreen();
	} else if(document.mozCancelFullScreen) {
		document.mozCancelFullScreen();
	} else if(document.oRequestFullscreen) {
		document.oCancelFullScreen();
	} else if(document.webkitExitFullscreen) {
		document.webkitExitFullscreen();
	} else {
		var docHtml = document.documentElement;
		var docBody = document.body;
		var videobox = document.getElementById('videobox');
		docHtml.style.cssText = "";
		docBody.style.cssText = "";
		videobox.style.cssText = "";
		document.IsFullScreen = false;
	}
}


判断是否处于全屏状态:

checkFull() {
	var isFull =  document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled;
	if(isFull === undefined) isFull = false;
	return isFull;
}
 
window.onresize = function(){
	if(!vm.checkFull()){
		vm.exitFull();//要执行的函数
	}
}


点击进入全屏

 
fullScreen() {
	var width = window.screen.width;
	var height = window.screen.height;
	var video = $('#backVideo')[0];
	$("#backVideo").css({
		'width': width,
		'height': height
	});//在进入全屏时改变Dom的宽高
	launchFullscreen(video);//开启全屏
}


点击退出全屏

exitFull() {
	var video = $('#backVideo')[0];
	$("#backVideo").css({
		'width': videoStyle.width,//在点击进入全屏前需记录原先的宽高,这里赋值后再退出全屏
		'height': videoStyle.height
	});
	exitFullscreen();//退出全屏
}