全屏和退出全屏时pc端很常用的一个功能,我们直接来看:
在HTML中添加两个按钮:
<button id="fullScreenBtn">进入全屏</button> <button id="exitFullScreenBtn">退出全屏</button>
JS的内容:
// 进入全屏 function requestFullScreen(element) { if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } } // 退出全屏 function exitFullScreen() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } } // 按钮点击事件 document.getElementById('fullScreenBtn').addEventListener('click', function() { requestFullScreen(document.documentElement); }); document.getElementById('exitFullScreenBtn').addEventListener('click', function() { exitFullScreen(); });
这样就可以通过点击按钮来实现全屏和退出全屏的功能。