我有2个全屏背景视频,我想根据一天中的时间进行动态更改(例如,循环播放白天的视频,从早上6点到晚上7点,而循环播放夜间视频,从7点到晚上6点)。目前,我正在评论我不想播放的视频。任何有关如何使用JS的建议都将不胜感激。 (视频位于名为“视频”的文件夹中。)
HTML:
<script>
if (document.cookie.indexOf("darkmode=1") >= 0) {
document.body.classList.add("dark-mode");
console.log("You enabled Dark Mode last time you were here!");
} else {
document.body.classList.remove("dark-mode");
console.log("You turned off Dark Mode last time you were here!");
}
</script>
CSS:
<div class="video_contain">
<!-- video day -->
<video autoplay loop id="video-background" muted plays-inline>
<source src="video/catbeats-loop-day-720p.m4v" poster="img/catbeats-day.gif" type="video/mp4">
</video>
<!-- video night -->
<!-- <video autoplay loop id="video-background" muted plays-inline>
<source src="video/catbeats-loop-night-720p.m4v" poster="img/catbeats-night.gif" type="video/mp4">
</video> -->
</div>
答案 0 :(得分:1)
尝试在一天中的某个小时使用js进行创建来创建src元素,然后将其附加到您的视频元素中,答案是从这篇文章中获得的。
changing source on html5 video tag
随时可以更正和改进此代码。
var currentTime = new Date().getHours();
var video = document.getElementById('video-background');
var source = document.createElement('source');
if (6 <= currentTime && currentTime < 7) {
source.setAttribute('src', 'https://storage.googleapis.com/coverr-main/mp4/The-Slow-Dock.mp4');
video.appendChild(source);
video.play();
}
else {
source.setAttribute('src', 'https://storage.googleapis.com/coverr-main/mp4/Night-Traffic.mp4');
video.appendChild(source);
video.play();
}
.video_contain {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
height: 100%;
overflow: hidden;
z-index: -100;
}
#video-background {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
margin: auto;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
}
<div class="video_contain">
<video autoplay loop id="video-background" muted plays-inline></video>
</div>