HTML5全屏API

這幾天一直在寫全屏查看的功能,沒想到HTML5中直接提供了全屏功能的API,看來之後事先應該先查一下HTML5有沒有提供相應的API。web

// 開啓全屏,必須手動觸發(好比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對象是同樣的,能夠用下面的方法區別開啓和退出全屏的兩種狀態:code

var fullscreenState = null;
document.addEventListener("fullscreenchange", function(e) {
		if(fullscreenState == 0){
			console.log("退出全屏");
			fullscreenstate = 1;
		}else{
			console.log("開啓全屏");
			fullscreenState = 0
		}
});

被全屏的元素必須是最外層window對象中的元素,好比iframe中的元素就沒法被全屏。對象

相關文章
相關標籤/搜索