js 控制浏览器全屏和退出全屏
# 场景
业务中,有些场景下需要调用 api 来控制 页面 和 元素 全屏以及退出全屏。
# API
MDN: Element.requestFullScreen
# 使用
# 源码实现
# 全屏
function fullScreen(el) { el = el || document.documentElement; const rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen; // 非 ie if (typeof rfs !== 'undefined' && rfs) { rfs.call(el); return; } // ie if (typeof window.ActiveXObject !== 'undefined') { const wscript = new ActiveXObject('WScript.Shell'); if (wscript) { wscript.SendKeys('{F11}'); } } }jscopy success
# 退出全屏
function exitFullScreen() { const el = document; const cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen; if (typeof cfs !== 'undefined' && cfs) { cfs.call(el); return; } if (typeof window.ActiveXObject !== 'undefined') { const wscript = new ActiveXObject('WScript.Shell'); if (wscript != null) { wscript.SendKeys('{F11}'); } } }jscopy success