專案中需要將後台瀏覽器的視窗全屏,也就是我們點擊一個按鈕要實現按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; }
附錄
1 一個在線的Demo
http://robnyman.github.io/fullscreen/
2 HTML5全螢幕API之網釣
3 jquery封裝的全螢幕外掛程式
http://johndyer.name/native-fullscreen-javascript-api-plus-jquery-plugin/
4 更細緻的全螢幕API介紹
4.1 https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Using_full_screen_mode
4.2 https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html
5 HTML5全螢幕API在FireFox/Chrome中的顯示差異
http://www.zhangxinxu.com/wordpress/2012/10/html5-full-screen-api-firefox-chrome-difference/