全屏操作必须由用户点击触发,且仅能调用 document.documentElement.requestFullscreen();状态需通过 document.fullscreenElement 判断,退出前须校验该值非 null;iframe 中需添加 allow="fullscreen" 属性。

按钮必须绑定 click 事件,不能用 setTimeout 或 input 触发
requestFullscreen() 被浏览器严格限制为仅响应**用户直接手势**,比如鼠标 click、触摸 tap。在页面加载时、定时器里、input/change 事件后自动调用,都会静默失败或抛出 NotAllowedError。
- ✅ 正确:给按钮加
addEventListener('click', ...),里面直接调用目标元素的requestFullscreen() - ❌ 错误:写在
setTimeout(() => el.requestFullscreen(), 0)里;或监听input后立刻调用 - ⚠️ 注意:
document.documentElement是最稳妥的目标(比document.body兼容性好),尤其在 Chrome/Firefox/Edge 中;Safari 对body调用常直接拒绝
状态判断只看 document.fullscreenElement,别维护布尔变量
全屏是全局状态,且可能被用户按 ESC、系统弹窗、多标签切换等外部行为中断。任何自己维护的 isFullscreen 变量都会迅速失真。
- ✅ 每次响应
fullscreenchange事件时,读取document.fullscreenElement—— 它要么是当前全屏的 DOM 元素,要么是null(注意不是undefined) - ✅ 判断是否为你的目标元素:
document.fullscreenElement === targetEl,而不是!!document.fullscreenElement - ⚠️ Safari 中该值更新有微延迟,建议用
Promise.resolve().then(() => { /* 读取 */ })避免取到旧状态
退出全屏必须先判空再调用 document.exitFullscreen()
document.exitFullscreen() 是全局方法,不接受参数,也不作用于某个元素。但它在未全屏时调用会抛出 NotFoundError(虽不中断脚本,但污染控制台)。
- ✅ 安全写法:
if (document.fullscreenElement) document.exitFullscreen(); - ✅ 更严谨:用
try...catch包裹,捕获NotFoundError和其他潜在异常 - ❌ 错误:写成
targetEl.exitFullscreen()—— 这个方法根本不存在 - ❌ 错误:对
document.body或未挂载的元素调用exitFullscreen()—— 它只认当前fullscreenElement
iframe 里全屏要加 allow="fullscreen" 属性
如果按钮或目标元素在 iframe 内,且你想让它全屏,浏览器默认禁止,除非显式声明权限。
立即学习“前端免费学习笔记(深入)”;
- ✅ 在 iframe 标签上加上
allow="fullscreen",例如:<iframe src="..." allow="fullscreen"></iframe> - ⚠️ 缺少该属性时,
requestFullscreen()会直接拒绝,错误名通常是NotAllowedError - ⚠️ 即使父页开了权限,iframe 内的子 iframe 仍需各自声明
allow="fullscreen"
实际中最容易被忽略的是 Safari 的状态延迟和 iframe 权限缺失——前者导致按钮文案不同步,后者让整个功能在嵌入场景下完全失效。



















