为什么调用exitFullscreen方法退出全屏时提示该方法不是函数?
问题诱因
全屏API的请求、退出方法挂载对象不同:
- 进入全屏的
requestFullscreen()方法挂载在具体DOM元素上,原有代码中调用document.documentElement.requestFullscreen()的写法符合规范 - 退出全屏的
exitFullscreen()方法仅挂载在全局document对象上,原有代码尝试在document.documentElement(页面根元素)上调用该方法,该对象下不存在对应属性,因此抛出exitFullscreen is not a function报错。
修复方案
仅需修改退出全屏逻辑的调用对象即可,核心修改点:把document.documentElement.exitFullscreen()替换为document.exitFullscreen()。
调用前可增加全屏状态判断,避免非全屏状态下调用引发的额外异常。
修正后的完整代码如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <button onclick="o()">O</button> <button onclick="x()">X</button> <script type="text/javascript" charset="utf-8"> function o(){ document.documentElement.requestFullscreen(); } function x(){ if(document.fullscreenElement) { document.exitFullscreen(); } } </script> </body> </html>
如需兼容旧版浏览器,可补充不同浏览器的前缀适配:
function exitFullscreen() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } }
内容的提问来源于stack exchange,提问作者Atif Arman aka Exotic Atif
相关产品推荐
相关产品推荐

