使用Javascript在页面加载时随机化背景视频



我想在页面加载时随机加载一个视频。我在本地存储了三个视频,我想在它们之间切换,但除了第一个视频外,似乎无法播放其他视频。我对Javascript很陌生,对需要修复的东西很不了解。。。谢谢你的帮助!

<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript">
var videoStorage = [
'/vid/background-video-1.mp4',
'/vid/background-video-2.mp4',
'/vid/background-video-3.mp4'
],
video = document.querySelector('video'),
activeVideoUrl = videoStorage[Math.round(Math.random() * (videoStorage.length - 1))];
</script>
</head>
<body>
<div class="overlay">
<video autoplay muted loop id="background-video">
<source src="/vid/background-video-1.mp4" type="video/mp4">
<source src="/vid/background-video-2.mp4" type="video/mp4">
<source src="/vid/background-video-3.mp4" type="video/mp4">
</video></div>

您的activeVideoUrl在页面加载时只设置一次。尝试使用setInterval更新activeVideoUrl的值。

您必须从此activeVideoUrl随机选择url设置src,您可以设置视频typeplay

你可以试试这个,

var videoStorage = [
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4',
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4',
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4'
],
video = document.querySelector('#background-video');
// DEFAULT PLAY ON PAGE LOAD
randomPlay();
// RANDOM PLAY FUNCTION
function randomPlay(){
let activeVideoUrl = videoStorage[
Math.round(Math.random() * (videoStorage.length - 1))
];
video.type = "video/mp4";
video.src = activeVideoUrl;
video.play();
}
<button onClick="randomPlay()">Random Play</button>
<div class="overlay">
<video autoplay muted loop id="background-video" height="150px"></video>
</div>

需要添加document.addEventListener("DOMContentLoaded", function ()

document.addEventListener("DOMContentLoaded", function () {
var videoStorage = [
'/vid/background-video-1.mp4',
'/vid/background-video-2.mp4',
'/vid/background-video-3.mp4'
],
video = document.querySelector('#background-video'),
activeVideoUrl = videoStorage[
Math.floor(Math.random() * (videoStorage.length))
];
video.type = "video/mp4";
video.src = activeVideoUrl;
});
</script>```

最新更新