用html5(requestFullscreen) js实现点击一个按钮使浏览器全屏效果

时间:2023-03-08 17:54:00

项目中需要将后台浏览器的窗口全屏,也就是我们点击一个按钮要实现按F11全屏的效果。 在HTML5中,W3C制定了关于全屏的API,就可以实现全屏幕的效果,也可以让页面中的图片,视频等全屏目前只有google chrome 15 +, safri5.1+,firfox10+,IE11支持 
查看例子,一睹为快!

全屏:

var docElm = document.documentElement;
//W3C
if (docElm.requestFullscreen) {
docElm.requestFullscreen();
}
//FireFox
else if (docElm.mozRequestFullScreen) {
docElm.mozRequestFullScreen();
}
//Chrome等
else if (docElm.webkitRequestFullScreen) {
docElm.webkitRequestFullScreen();
}
//IE11
else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
}

  退出全屏:

if (document.exitFullscreen) {
document.exitFullscreen();
}
else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
}
else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
else if (document.msExitFullscreen) {
document.msExitFullscreen();
}

  事件监听:

document.addEventListener("fullscreenchange", function () {
fullscreenState.innerHTML = (document.fullscreen)? "" : "not ";}, false); document.addEventListener("mozfullscreenchange", function () {
fullscreenState.innerHTML = (document.mozFullScreen)? "" : "not ";}, false); document.addEventListener("webkitfullscreenchange", function () {
fullscreenState.innerHTML = (document.webkitIsFullScreen)? "" : "not ";}, false); document.addEventListener("msfullscreenchange", function () {
fullscreenState.innerHTML = (document.msFullscreenElement)? "" : "not ";}, false);

  全屏样式设置 :

在浏览器全屏的使用我们还可以进行样式设置

代码如下:
html:-moz-full-screen {
background: red;
} html:-webkit-full-screen {
background: red;
} html:fullscreen {
background: red;
}