如何实现视频适配屏幕并禁用滚动?视频溢出屏幕问题排查
视频适配屏幕+禁用滚动的问题分析与修复
需求与当前问题
需求:实现视频全屏适配屏幕,同时禁用页面滚动
当前问题:视频未全屏显示,页面出现溢出滚动
代码存在的问题
- 未重置
html和body的默认边距/内边距:浏览器默认会给body设置8px左右的margin,导致容器无法完全贴合视口边缘,进而出现溢出 - 视频容器高度设置不合理:仅用
height:auto会让视频保持原比例,但无法保证填满整个视口高度,当视频宽高比与视口不一致时,要么上下留白,要么横向溢出 - 未添加禁用页面滚动的逻辑:没有限制
html/body的滚动行为 - 未适配播放器内部元素:indigo-player初始化后生成的视频元素,需要配合容器样式实现全屏适配
修复后的完整代码
<!DOCTYPE html> <html> <head> <style> /* 重置默认样式+禁用滚动 */ html, body { margin: 0; padding: 0; overflow: hidden; /* 禁用页面滚动 */ height: 100%; /* 确保根元素占满视口高度 */ } .videosize { position: absolute; z-index: -1; top: 0; left: 0; width: 100vw; /* 占满视口宽度 */ height: 100vh; /* 占满视口高度 */ } /* 适配indigo-player内部的视频元素 */ .videosize video { width: 100%; height: 100%; object-fit: cover; /* 保持视频比例,填满容器,超出部分裁剪 */ /* 如果需要完整显示视频(可能留边),改用 object-fit: contain; */ } </style> <script src="https://cdn.jsdelivr.net/npm/indigo-player@1/lib/indigo-player.js"></script> </head> <body> <div id="playerContainer" class="videosize"></div> <script> const config = { sources: [ { type: 'hls', src: 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8', } ], }; const element = document.getElementById('playerContainer'); const player = IndigoPlayer.init(element, config); </script> </body> </html>
关键修改说明
- 给
html和body添加margin:0;padding:0消除默认间距,overflow:hidden直接禁用页面滚动,height:100%确保根元素高度铺满视口 - 容器改用
width:100vw和height:100vh,强制占满整个视口的宽高 - 给内部视频元素设置
object-fit:cover,让视频在保持比例的前提下填满容器,避免留白或溢出(如果需要完整显示视频内容,可替换为object-fit:contain)
内容的提问来源于stack exchange,提问作者YBerkayAltin
相关产品推荐
相关产品推荐

