You need to enable JavaScript to run this app. 如何实现while loop循环触发fullscreen模式,解决网页崩溃问题
优惠活动
大模型
产品
解决方案
定价
更多

如何实现while loop循环触发fullscreen模式,解决网页崩溃问题

循环全屏功能实现方案

原代码问题原因

  • JavaScript无原生同步wait()方法,你写的等待逻辑完全不生效
  • 同步无限while循环会阻塞JS主线程,直接卡死页面渲染和事件响应,导致网页崩溃
  • 未做浏览器全屏兼容处理,也没有判断当前全屏状态,容易调用报错
  • 浏览器安全策略限制全屏API必须由用户主动交互(点击、按键等)触发,无交互自动调用会被直接拦截

修复后可运行代码

// 全局变量控制循环启停
let fullscreenLoopTimer = null;

function startFullscreenLoop() {
  // 避免重复启动创建多个定时器
  if (fullscreenLoopTimer) clearInterval(fullscreenLoopTimer);

  // 每3秒执行一次全屏逻辑,替代同步while循环
  fullscreenLoopTimer = setInterval(() => {
    const rootEle = document.documentElement;
    const myVideo = document.getElementById("myVideo");
    const otherContent = document.getElementById("everything");

    myVideo.style.display = "inline-block";
    otherContent.style.display = "none";

    // 仅在非全屏状态下调用全屏接口,避免重复报错
    if (!document.fullscreenElement) {
      // 兼容不同浏览器的全屏API
      if (rootEle.requestFullscreen) {
        rootEle.requestFullscreen();
      } else if (rootEle.webkitRequestFullscreen) {
        rootEle.webkitRequestFullscreen();
      } else if (rootEle.msRequestFullscreen) {
        rootEle.msRequestFullscreen();
      }
    }
  }, 3000)
}

// 可调用此方法停止循环
function stopFullscreenLoop() {
  if (fullscreenLoopTimer) {
    clearInterval(fullscreenLoopTimer);
    fullscreenLoopTimer = null;
  }
}

// 示例:绑定按钮点击事件启动,必须由用户交互触发
document.addEventListener('DOMContentLoaded', () => {
  const startButton = document.getElementById('startBtn');
  if (startButton) {
    startButton.addEventListener('click', startFullscreenLoop);
  }
})

使用注意事项

  • 需要在页面中新增一个id为startBtn的按钮,用户点击后才会启动循环,这是浏览器安全策略的强制要求,无法绕过
  • 如果需要调整等待时长,修改setInterval的第二个参数即可,单位为毫秒,3000对应3秒
  • 代码已做多浏览器兼容,覆盖Chrome、Safari、IE等主流浏览器的全屏调用规则

内容的提问来源于stack exchange,提问作者user15343564

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 06:45:03