这几天一直在写全屏查看的功能,没想到HTML5中直接提供了全屏功能的API,看来以后事先应该先查一下HTML5有没有提供相应的API。
// 开启全屏,必须手动触发(比如click),不能自动全屏,参数为被全屏的元素
function launchFullScreen(element) {
if(element.requestFullScreen) {
element.requestFullScreen();
}else if(element.mozRequestFullScreen) { //兼容moz
element.mozRequestFullScreen();
}else if(element.webkitRequestFullScreen) { //兼容webkit
element.webkitRequestFullScreen();
}
}
//退出全屏
function exitFullscreen() {
if(document.exitFullscreen) {
document.exitFullscreen();
}else if(document.mozCancelFullScreen) { //兼容moz
document.mozCancelFullScreen();
}else if(document.webkitExitFullscreen) { //兼容webkit
document.webkitExitFullscreen();
}
}
另外开启全屏和退出全屏的监听事件,可以写一些回调函数
document.addEventListener("fullscreenchange", function(e) {
console.log("fullscreenchange", e);
});
document.addEventListener("mozfullscreenchange", function(e) {
console.log("mozfullscreenchange ", e);
});
document.addEventListener("webkitfullscreenchange", function(e) {
console.log("webkitfullscreenchange", e);
});
document.addEventListener("msfullscreenchange", function(e) {
console.log("msfullscreenchange", e);
});
开启全屏和退出全屏所返回的event对象是一样的,可以用下面的方法区别开启和退出全屏的两种状态:
var fullscreenState = null;
document.addEventListener("fullscreenchange", function(e) {
if(fullscreenState == 0){
console.log("退出全屏");
fullscreenstate = 1;
}else{
console.log("开启全屏");
fullscreenState = 0
}
});
被全屏的元素必须是最外层window对象中的元素,比如iframe中的元素就无法被全屏。