You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么调用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 20:12:02