可通过requestFullscreen API、document.documentElement全屏、F11键盘监听、CSS模拟及权限校验五种方式实现HTML5视频全屏。需注意浏览器兼容性、用户交互触发限制及降级处理。

如果您希望在网页中通过 HTML5 视频元素实现全屏播放,可使用原生 JavaScript 的 requestFullscreen API 或借助浏览器快捷键触发全屏。以下是具体操作方式:
一、使用 requestFullscreen API 触发视频全屏
该方法通过调用视频元素的 requestFullscreen() 方法,使视频容器进入全屏模式,适用于现代主流浏览器(Chrome、Firefox、Edge、Safari 10+),需注意浏览器前缀兼容性及用户交互触发限制。
1、确保视频元素已设置 id 属性,例如:。
2、为视频添加点击事件监听器,绑定全屏请求逻辑:document.getElementById('myVideo').addEventListener('click', function() { this.requestFullscreen(); });。
立即学习“前端免费学习笔记(深入)”;
3、针对不同浏览器内核补充兼容写法:若调用失败,尝试 this.webkitRequestFullscreen()(Safari)、this.mozRequestFullScreen()(Firefox)或 this.msRequestFullscreen()(旧版 Edge)。
二、通过 document.documentElement 调用全屏 API
当需要将整个页面(含视频及其父容器)以全屏方式展示时,可对 document.documentElement 调用 requestFullscreen,避免仅视频元素拉伸变形,同时保持布局完整性。
1、获取视频所在最外层容器,例如:const container = document.querySelector('.video-wrapper');。
2、绑定按钮点击事件,执行全屏请求:container.requestFullscreen ? container.requestFullscreen() : container.webkitRequestFullscreen ? container.webkitRequestFullscreen() : container.msRequestFullscreen();。
3、添加全屏状态监听,防止重复调用:document.addEventListener('fullscreenchange', () => { if (!document.fullscreenElement) { console.log('已退出全屏'); } });。
三、监听键盘事件模拟 F11 全屏行为
F11 是浏览器原生全屏快捷键,无法通过 JavaScript 直接触发,但可通过监听 keydown 事件,在用户按下 F11 时执行自定义逻辑(如显示提示、切换 UI 样式),增强体验一致性。
1、监听全局键盘事件:document.addEventListener('keydown', function(e) { if (e.key === 'F11') { e.preventDefault(); } });。
2、在 F11 按下时,判断当前是否处于全屏状态并作出响应:if (e.key === 'F11' && !document.fullscreenElement) { document.documentElement.requestFullscreen(); }。
3、为防止干扰系统级 F11 行为,仅在视频区域获得焦点时启用该监听:myVideo.addEventListener('focus', () => { document.addEventListener('keydown', handleF11); });。
四、CSS 辅助实现视觉全屏效果
当 requestFullscreen API 不可用或被禁用时,可通过 CSS 将视频元素强制撑满视口,模拟全屏观感,适用于降级方案或嵌入式环境。
1、定义全屏样式类:.video-fullscreen { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 9999; }。
2、通过 JavaScript 切换该类:myVideo.classList.add('video-fullscreen');。
3、退出时移除类并重置宽高:myVideo.classList.remove('video-fullscreen'); myVideo.style.width = ''; myVideo.style.height = '';。
五、处理全屏 API 的权限与安全限制
现代浏览器要求全屏请求必须由用户手势(如 click、touchstart)直接触发,禁止在异步回调(如 setTimeout、fetch.then)中调用,否则会抛出 TypeError 异常。
1、确保 requestFullscreen 调用位于事件处理函数第一层作用域:button.addEventListener('click', () => video.requestFullscreen());。
2、避免在 Promise 回调中调用:fetch('/video.mp4').then(() => video.requestFullscreen()); // 错误示例,将被拒绝。
3、检查 API 可用性后再调用:if (video.requestFullscreen && document.fullscreenEnabled) { video.requestFullscreen(); }。










