JS实现浏览器全屏

发表于:2017-11-07

在键盘上可以按F11全屏,ESC退出全屏, 不过有时候需要点击就有这个需求了, 坑爹的是在标准草案中没有浏览器支持,都有自己的标准实现。

在线预览

全屏显示

// documentElement 指的是html元素
var docElm = document.documentElement;
// 标准草案
if (docElm.requestFullscreen) {  
    docElm.requestFullscreen();  
}
// Firefox  
else if (docElm.mozRequestFullScreen) {  
    docElm.mozRequestFullScreen();  
}
// 基于WebKit
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();
}

事件监听

单单靠前面2个API还是不够的,这里主要是判断document.fullscreen他是一个布尔值,全屏是true。

document.addEventListener("fullscreenchange", function () {  
    text.innerHTML = document.fullscreen ? trueFullscreen : falseFullscreen;
});  

document.addEventListener("mozfullscreenchange", function () {  
    text.innerHTML = document.mozFullScreen ? trueFullscreen : falseFullscreen;
});  

document.addEventListener("webkitfullscreenchange", function () {  
    text.innerHTML = document.webkitIsFullScreen ? trueFullscreen : falseFullscreen;
});
document.addEventListener("msfullscreenchange", function () {
    text.innerHTML = document.msFullscreenElement ? trueFullscreen : falseFullscreen;
});

样式

还提供了全屏后的选择器点个赞!

html:-moz-full-screen {  
    background: #ccc;
}  

html:-webkit-full-screen {  
    background: #ccc;  
}  

html:fullscreen {  
    background: #ccc;
}
JavaScript HTML
广告