如何在单页网站上随机刷新背景视频?

How can I randomize a background video on refresh on a one page website?

我目前正在使用 Bulma 框架开发一个单页网站项目,我的网站目前有一个背景视频,当用户滚动浏览网站时播放。但是,我想添加更多视频并在刷新时随机播放不同的视频。我找到了有效的 JS 代码,但它从互联网上提取视频,而我的视频保存在一个文件夹中;当我输入文件名时,它不起作用。

这是最初对我有用的 JS 代码

var videoStorage = [ 
'//media.w3.org/2010/05/sintel/trailer',
'//techslides.com/demos/sample-videos/small',
'//fat.gfycat.com/DazzlingCompleteAnkole',
'//zippy.gfycat.com/HeavyPlumpIvorybilledwoodpecker'
],
    video = document.querySelector('video'),
    // choose one random url from our storage as the active video
    activeVideoUrl = videoStorage[Math.round(Math.random() * (videoStorage.length - 1))];        

// check which file extension your browser can play and set the video source accordingly
if(video.canPlayType('video/webm')) {
    video.setAttribute('src', activeVideoUrl + '.webm');
} else if(video.canPlayType('video/mp4')) {
    video.setAttribute('src', activeVideoUrl + '.mp4');
}

这是 HTML 目前我只有一个视频

<section id="home" class="hero is-fullheight-with-navbar video">
    <div class="hero-video">
        <video id="bgvid" playsinline autoplay muted loop>
            <source src="images/i_know_what_i_like.mp4" type="video/mp4">
        </video>
    </div>

既然 JS 代码确实完成了它的工作,有没有办法使用我保存在文件夹中的文件让它工作?

阅读笔记。我希望您的 url 没有加载,因为您提供了扩展名。例如:images/i_know_what_i_like.mp4 会变成 images/i_know_what_i_like.mp4.mp4images/i_know_what_i_like.mp4.webp,它们可能不存在 url。

一种解决方案是不使用 JS 添加扩展。

// NOTE: make sure these are valid working urls.
var videoStorage = [ 
'images/i_know_what_i_like.mp4'
];
let video = document.querySelector('video');
// choose one random url from our storage as the active video
// NOTE: you don't want to use Math.round() here, use Math.floor() instead
let activeVideoUrl = videoStorage[Math.floor(Math.random() * videoStorage.length];        

// NOTE: you are providing the extension so no need to add it in JS
video.setAttribute('src', activeVideoUrl);

也许你应该使用完整路径:

    var videoStorage = [ 
     'https://example.com/videso/test1.mp4',
     'https://example.com/videso/test2.mp4',
     'https://example.com/videso/test3.mp4',
     'https://example.com/videso/test4.mp4',
     'https://example.com/videso/test5.mp4'
    ],
        video = document.querySelector('video'),
        // choose one random url from our storage as the active video
        activeVideoUrl = videoStorage[Math.round(Math.random() * (videoStorage.length - 1))];        

  video.setAttribute('src', activeVideoUrl)