【发布时间】:2021-11-14 12:49:13
【问题描述】:
这是我想要实现的目标:我在一个数组中有一堆剪辑,我希望所有这些剪辑都随机无缝地显示(使用预加载选项)作为背景视频。我拿了一些我在另一篇文章中找到的代码,到目前为止,我已经能够使第一个视频被随机选择,但是其余的视频继续按顺序显示(包括在数组中)。您将如何修改此代码以使所有代码(不仅是第一个代码)都随机显示?我想对你们大多数人来说解决这个问题应该很容易,但我不是程序员,所以如果你们中的任何人能帮助我,那就太好了。提前致谢。这是我当前的代码:
<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)
{
nextActiveVideo = ++nextActiveVideo % vidSources.length;
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>
<body>
<div id="videoContainer"></div>
</body>
video {
object-fit: cover;
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
}
#videoContainer {
display: inline-block;
}
【问题讨论】:
-
idk 是否可行,懒得深入测试,但可能在
video.onended,先做nextActiveVideo = Math.floor((Math.random() * vidSources.length));。 -
成功了!!!谢谢:)
标签: javascript arrays random html5-video preload