等比例缩放视频墙最大化覆盖率布局实现技术咨询
补全后完整代码
let VideoCount = $("#Stage").find('video').length; let stageW = $("#Stage").outerWidth(); let stageH = $("#Stage").outerHeight(); // 预计算布局基础参数 let perRowCount, rowCount; if (VideoCount === 1) { perRowCount = 1; rowCount = 1; } else if (VideoCount <= 3) { perRowCount = VideoCount; rowCount = 1; } else { perRowCount = 2; rowCount = Math.ceil(VideoCount / 2); } // 每行最大允许高度 const perRowMaxHeight = stageH / rowCount; const $videos = $("#Stage").find('video'); const rowRatioSumList = []; // 预计算每行所有视频的宽高比总和,用于后续行高计算 for (let i = 0; i < VideoCount; i += perRowCount) { let currentRowRatioSum = 0; for (let j = i; j < Math.min(i + perRowCount, VideoCount); j++) { const video = $videos[j]; currentRowRatioSum += video.videoWidth / video.videoHeight; } rowRatioSumList.push(currentRowRatioSum); } $videos.each(function(index) { var srcVideoW = this.videoWidth; var srcVideoH = this.videoHeight; const videoRatio = srcVideoW / srcVideoH; // 确定当前视频所属行 const currentRowIndex = Math.floor(index / perRowCount); // 计算当前行最优统一高度:取行高上限和填满行宽所需高度的最小值,避免溢出同时最大化覆盖率 const currentRowBestHeight = Math.min(perRowMaxHeight, stageW / rowRatioSumList[currentRowIndex]); // 按原始比例计算当前视频宽度 var BestWidth = videoRatio * currentRowBestHeight; var BestHeight = currentRowBestHeight; $(this).css("float", "left"); $(this).css("display", "inline-block"); $(this).css("width", BestWidth+"px"); $(this).css("height", BestHeight+"px"); });
核心规则适配说明
- 布局规则完全匹配要求:1个视频单列适配舞台,2-3个单行排布,4个及以上每行2个
- 所有视频保持原始宽高比缩放,无拉伸变形
- 同排视频高度完全一致,且会自动适配行宽/行高上限,实现舞台最大覆盖率
- 边缘场景兼容:哪怕最后一行不足2个视频,也会自动适配行宽,不会出现错位
内容的提问来源于stack exchange,提问作者Conrad
相关产品推荐
相关产品推荐

