js 设置、退出和判断全屏的方法
- 设置全屏
- 退出全屏
- 全屏属性
- 全屏事件
- 全屏状态的CSS
设置全屏
/**
* [setFullscreen 设置全屏]
* @param {domElement} element [DOM节点对象(可选)]
*/
function setFullscreen(element) {
var el = element instanceof HTMLElement ? element : document.documentElement;
var rfs = el.requestFullscreen ||
el.webkitRequestFullscreen ||
el.mozRequestFullScreen ||
el.msRequestFullscreen;
if (rfs) {
rfs.call(el);
} else if (window.ActiveXObject) {
var ws = new ActiveXObject("WScript.Shell");
ws && ws.SendKeys("{F11}");
}
}
退出全屏
/**
* [exitFullscreen 退出全屏]
*/
function exitFullscreen(){
var efs = document.exitFullscreen ||
document.webkitExitFullscreen ||
document.mozCancelFullScreen ||
document.msExitFullscreen;
if (efs) {
efs.call(document);
} else if (window.ActiveXObject) {
var ws = new ActiveXObject("WScript.Shell");
ws && ws.SendKeys("{F11}");
}
}
属性
fullscreenElement
var fullscreenElement = document.fullscreenElement ||
document.mozFullScreenElement ||
document.webkitFullscreenElement;
fullscreenElement属性返回正处于全屏状态的Element节点,如果当前没有节点处于全屏状态,则返回null。
fullscreenEnabled
var fullscreenEnabled = document.fullscreenEnabled ||
document.mozFullScreenEnabled ||
document.webkitFullscreenEnabled ||
document.msFullscreenEnabled;
if (fullscreenEnabled) {
setFullscreen();
} else {
console.log('浏览器当前不能全屏');
}
fullscreenEnabled属性返回一个布尔值,表示当前文档是否可以切换到全屏状态。
判断全屏
fullscreenchange
document.addEventListener('fullscreenchange', function(){});
document.addEventListener('webkitfullscreenchange', function(){});
document.addEventListener('mozfullscreenchange', function(){});
document.addEventListener('MSFullscreenChange', function(){});
fullscreenchange事件:浏览器进入或离开全屏时触发。
fullscreenerror
document.addEventListener('fullscreenerror', function(){});
document.addEventListener('webkitfullscreenerror', function(){});
document.addEventListener('mozfullscreenerror', function(){});
document.addEventListener('MSFullscreenError', function(){});
fullscreenerror事件:浏览器无法进入全屏时触发,可能是技术原因,也可能是用户拒绝。
更详细的全屏判断请点击这里
全屏状态下的CSS
:-webkit-full-screen {
/* properties */
}
:-moz-full-screen {
/* properties */
}
:-ms-fullscreen {
/* properties */
}
:full-screen { /*pre-spec */
/* properties */
}
:fullscreen { /* spec */
/* properties */
}
/* deeper elements */
video:-webkit-full-screen {
width: 100%;
height: 100%;
}
全屏状态下,大多数浏览器的CSS支持:full-screen伪类,只有IE11支持:fullscreen伪类。使用这个伪类,可以对全屏状态设置单独的CSS属性。
目录
浏览器兼容
- IE11+
- Chrome
- FireFox
参考链接
http://javascript.ruanyifeng.com/htmlapi/fullscreen.html#toc7