HTML5实现网页的全屏切换
使用HTML5提供的JavaScript Api可以实现主流浏览器的全屏和退出全屏操作,封装成进入全屏和退出全屏的函数如下:
1 //进入全屏 2 function enterFullScreen() { 3 var de = document.documentElement; 4 if (de.requestFullscreen) { 5 de.requestFullscreen(); 6 } else if (de.mozRequestFullScreen) { 7 de.mozRequestFullScreen(); 8 } else if (de.webkitRequestFullScreen) { 9 de.webkitRequestFullScreen(); 10 } 11 } 12 //退出全屏 13 function exitFullScreen() { 14 var de = document; 15 if (de.exitFullscreen) { 16 de.exitFullscreen(); 17 } else if (de.mozCancelFullScreen) { 18 de.mozCancelFullScreen(); 19 } else if (de.webkitCancelFullScreen) { 20 de.webkitCancelFullScreen(); 21 } 22 }
然后将这两个函数绑定到超链接或者按钮事件上就可以实现浏览器的开启全屏和退出全屏操作
简单的测试页面代码如下:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>全屏切换</title> 6 <script type="text/javascript"> 7 //进入全屏 8 function enterFullScreen() { 9 var de = document.documentElement; 10 if (de.requestFullscreen) { 11 de.requestFullscreen(); 12 } else if (de.mozRequestFullScreen) { 13 de.mozRequestFullScreen(); 14 } else if (de.webkitRequestFullScreen) { 15 de.webkitRequestFullScreen(); 16 } 17 } 18 //退出全屏 19 function exitFullScreen() { 20 var de = document; 21 if (de.exitFullscreen) { 22 de.exitFullscreen(); 23 } else if (de.mozCancelFullScreen) { 24 de.mozCancelFullScreen(); 25 } else if (de.webkitCancelFullScreen) { 26 de.webkitCancelFullScreen(); 27 } 28 } 29 </script> 30 </head> 31 <body> 32 <div> 33 <a href="javascript:;" onclick="enterFullScreen()">进入全屏</a> 34 35 <a href="javascript:;" onclick="exitFullScreen()">退出全屏</a> 36 </div> 37 </body> 38 </html>
当点击进入全屏时,当前页面会进入全屏状态,并且浏览器会发出提示
当点击退出全屏时将会退出全屏状态