如何使用JavaScript实现多背景视频随机无缝循环及现有代码修改
问题定位
你当前代码仅首视频随机的核心原因是onplaying回调中使用了nextActiveVideo = ++nextActiveVideo % vidSources.length的自增逻辑,后续播放索引是按数组顺序依次递增的,没有重新随机计算。
修改说明
只需要把上述自增逻辑替换为随机索引生成逻辑即可,新增了防连续重复播放的判断,避免同一个片段连续播放影响效果,原有预加载、无缝切换的逻辑全部保留。
完整可运行代码
CSS 样式
video { object-fit: cover; width: 100vw; height: 100vh; position: fixed; top: 0; left: 0; } #videoContainer { display: inline-block; }
HTML 结构
<body> <div id="videoContainer"></div> </body>
JavaScript 逻辑
<script> var videoContainer = document.getElementById('videoContainer'), output = document.getElementById('output'), nextVideo, videoObjects = [ document.createElement('video'), document.createElement('video') ], vidSources = [ "clip1.mov", "clip2.mov", "clip3.mov", "clip4.mov", ], nextActiveVideo = Math.floor((Math.random() * vidSources.length)); videoObjects[0].inx = 0; videoObjects[1].inx = 1; initVideoElement(videoObjects[0]); initVideoElement(videoObjects[1]); videoObjects[0].autoplay = true; videoObjects[0].src = vidSources[nextActiveVideo]; videoContainer.appendChild(videoObjects[0]); videoObjects[1].style.display = 'none'; videoContainer.appendChild(videoObjects[1]); function initVideoElement(video) { video.playsinline = true; video.muted = false; video.preload = 'auto'; video.onplaying = function(e) { // 替换原有的自增逻辑,生成不重复的随机索引 let newActiveVideo; do { newActiveVideo = Math.floor(Math.random() * vidSources.length); } while (newActiveVideo === nextActiveVideo); nextActiveVideo = newActiveVideo; if(this.inx == 0) nextVideo = videoObjects[1]; else nextVideo = videoObjects[0]; nextVideo.src = vidSources[nextActiveVideo]; nextVideo.pause(); }; video.onended = function(e) { this.style.display = 'none'; nextVideo.style.display = 'block'; nextVideo.play(); }; } </script>
内容的提问来源于stack exchange,提问作者RGM
相关产品推荐
相关产品推荐

