本文主要是介绍js 页面全屏,退出全屏, fullScreen,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
项目有个需求,当点击打开一个新页面的时候需要该页面全屏(类似F11键功能),查找之后发现没办法直接用js来触发全屏,只能通过用户鼠标、键盘等事件中才能触发,即“对于一些非用户事件,比如onload、timeout等之类的事件中调用requestFullScreen是无法生效的,出于安全性考虑必须在用户事件中调用,比如鼠标、键盘等操作”。
文档全屏的方法本身是作用在body或documentElement上的,也可以作用的元素本身上,其他元素如CANVAS、VIDEO,之类的也可以发起全屏请求。
作用在document的全屏代码
function fullScreen(){var docElm = document.documentElement; if (docElm.requestFullscreen) { docElm.requestFullscreen(); } else if (docElm.mozRequestFullScreen) {docElm.mozRequestFullScreen(); } else if (docElm.webkitRequestFullScreen) {docElm.webkitRequestFullScreen(); } else if (elem.msRequestFullscreen) {elem.msRequestFullscreen();}
}
作用在document的关闭全屏代码
function closeFullScreen(){if (document.exitFullscreen) { document.exitFullscreen(); }else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); }else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); }else if (document.msExitFullscreen) {document.msExitFullscreen();}}
基于元素全屏的代码
<!--html code--><div id="content" style="width:500px;height:500px;background:red;">这是被全屏的元素<button id='btn'>全屏</button><button id="closeBtn">退出全屏</button> </div>
//js code
function fullScreen(el) { var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen, wscript; if(typeof rfs != "undefined" && rfs) { rfs.call(el); return; } if(typeof window.ActiveXObject != "undefined") { wscript = new ActiveXObject("WScript.Shell"); if(wscript) { wscript.SendKeys("{F11}"); } }
}
function exitFullScreen(el) { var el= document, cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen, wscript; if (typeof cfs != "undefined" && cfs) { cfs.call(el); return; } if (typeof window.ActiveXObject != "undefined") { wscript = new ActiveXObject("WScript.Shell"); if (wscript != null) { wscript.SendKeys("{F11}"); } }
} var btn = document.getElementById('btn');
var content = document.getElementById('content'); //被全屏显示的元素
btn.onclick = function(){ fullScreen(content);
}
var closeBtn = document.getElementById('closeBtn');
closeBtn.onclick = function(){ exitFullScreen();
}
这篇关于js 页面全屏,退出全屏, fullScreen的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!