我有这个带有3个来源的<video>
标签,希望将它们随机化,并在我的网站加载后选择一个:
<video autoplay muted loop id="video_mainhub" style="width: 100%;height: auto;position:absolute;z-index: -1">
<source src="./video/vid95.mp4" type="video/mp4">
<source src="./video/vid70.mp4" type="video/mp4">
<source src="./video/vid65.mp4" type="video/mp4">
</video>
谢谢。
答案 0 :(得分:0)
对于遇到相同问题的人,以下是解决方法:
<video src="./video/vid95.mp4" autoplay muted loop id="video_mainhub"></video>
和javascript:
var vidElement = document.getElementById('video_mainhub');
var vidSources = [
"./video/vid95.mp4",
"./video/vid70.mp4",
];
var activeVideo = Math.floor((Math.random() * vidSources.length));
vidElement.src = vidSources[activeVideo];
vidElement.addEventListener('ended', function(e) {
// update the active video index
activeVideo = (++activeVideo) % vidSources.length;
if(activeVideo === vidSources.length){
activeVideo = 0;
}
// update the video source and play
vidElement.src = vidSources[activeVideo];
vidElement.play();
});