js全屏操作api
参考MDN全屏api文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Fullscreen_API
网上搜索的大多是通过SendKeys的方式传入f11来模拟f11全屏操作,
可都2020年啦~js早就有支持全屏操作的api了
适配各大内核主流浏览器,代码:
var docElm = document.documentElement //W3C if (docElm.requestFullscreen) { docElm.requestFullscreen() } //FireFox else if (docElm.mozRequestFullScreen) { docElm.mozRequestFullScreen() } //Chrome等 else if (docElm.webkitRequestFullScreen) { docElm.webkitRequestFullScreen() } //IE11 else if (elem.msRequestFullscreen) { elem.msRequestFullscreen() }
关闭全屏操作,代码:
//W3C if (document.exitFullscreen) { document.exitFullscreen() } //FireFox else if (document.mozCancelFullScreen) { document.mozCancelFullScreen() } //Chrome等 else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen() } //IE11 else if (document.msExitFullscreen) { document.msExitFullscreen() }
网站上的具体实现
具体效果查看网站右下角即可,f12仔细看控制全屏按钮的代码,不难发现有一个自定义属性
data-full
的值就是用来区别当前是全屏还是正常屏幕视口的参数
将上述两个代码块封装成一个方法:
function requestFullScreen(ele) { let full = ele.data("full"); if (full != "full") { var docElm = document.documentElement //W3C if (docElm.requestFullscreen) { docElm.requestFullscreen() } //FireFox else if (docElm.mozRequestFullScreen) { docElm.mozRequestFullScreen() } //Chrome等 else if (docElm.webkitRequestFullScreen) { docElm.webkitRequestFullScreen() } //IE11 else if (elem.msRequestFullscreen) { elem.msRequestFullscreen() } ele.data("full","full"); } else { //W3C if (document.exitFullscreen) { document.exitFullscreen() } //FireFox else if (document.mozCancelFullScreen) { document.mozCancelFullScreen() } //Chrome等 else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen() } //IE11 else if (document.msExitFullscreen) { document.msExitFullscreen() } ele.data("full","half"); } }
直接使用即可,绑定按钮点击事件传入按钮的DOM节点
$("#screen-control").on( "click", function() { requestFullScreen($("#screen-control")); } );
是不是很简单呐~
🎨 原创不易,支持请点赞、转载请注明本文作者为子成君