有一个pad端需求,要求进到项目之后在浏览器中将整个项目全屏,
window.onload = () => { let element = document.documentElement if (element.requestFullscreen) { element.requestFullscreen() } else if (element.msRequestFullscreen) { // 兼容ie element.msRequestFullscreen() } else if (element.mozRequestFullScreen) { // 兼容火狐 element.mozRequestFullScreen() } else if (element.webkitRequestFullscreen) { // 兼容chrome和safari element.webkitRequestFullscreen() } } }
是在main.js中写的script标签中实现的
会报错,Failed to execute ‘requestFullscreen’ on ‘Element’: API can only be initiated by a user gesture.
原因在于需要用户点击按钮触发事件,不允许onload触发,会用安全性问题。
可能本来这个需求也有点扯淡
通过判断元素的requestFullscreen函数是否存在与document.fullscreenEnabled是否为True判断浏览器是否支持全屏或启用全屏,兼容写法为
function supportfull(){ var requestFullscreen = document.body.requestFullscreen || document.body.webkitRequestFullscreen || document.body.mozRequestFullScreen || document.body.msRequestFullscreen; var fullscreenEnabled = document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled || document.msFullscreenEnabled; return !!(requestFullscreen && fullscreenEnabled); }
判断当前是否全屏
通过document.fullscreenElement属性是否为空来判断,对于webkit内核的浏览器,还可以通过document.webkitIsFullScreen属性来判断,以下为兼容写法
function isfull() { return !!(document.webkitIsFullScreen || fullele()); }
退出全屏
通过document.exitFullscreen方法来退出全屏,对于不同内核的浏览器,方法名除了前缀不一样外,其他地方也不一样,以下为兼容写法
function exitfull() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } }