在页面加载时播放随机播放的<video>

时间:2019-07-09 21:50:26

标签: javascript jquery html

我有这个带有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>

谢谢。

1 个答案:

答案 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();
});