上下文:html页面上的多个视频。我的 html 页面上有多个视频。我希望一个视频在美国东部标准时间每天中午 11:00 出现(并自动播放(,第二个视频在 12:00 出现,依此类推。这可以用JavaScript和HTML来实现吗?
是的,可能吗。
假设您的 DOM 中有一个 id 为 myVideoElementID
的视频元素
display: none
。使用这个函数,我写道:
function showElementAndPlayVideo(id) {
const myElement = document.querySelector("#" + id);
myElement.style.display = 'block'; // this will make the element visible
myFunctionToPlayVideo(id); // your implementation which depends on the video player you are using
}
function showElementAtTime(id, hour) {
var now = new Date();
var time = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, 0, 0, 0) - now;
var timeEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, 59, 59, 0) - now;
if(now >= time && now < timeEnd) { // show and play right now since it's in the period
showElementAndPlayVideo(id);
} else if(time < now) { // show and play later because it's not yet the time
setTimeout(() => showElementAndPlayVideo(id), now - time);
}
}
您可以在页面加载时调用showElementAtTime('myVideoElementID', 11)
。这将使您的视频元素(以前隐藏(在 11:00:00 - 11:59:59 时间段内可见。
我会使用两个并行数组。一个用于存放应播放视频的时间,另一个用于存放要播放的视频的来源。
然后,我会每分钟检查一次,看看时间是否包含在第一个数组中。
// Default time functions in JavaScript return single digit hours/minutes.
var timesToPlayVideos = [
"8:7",
"9:30",
"10:45",
"11:15",
"12:0",
"13:0",
],
videoSources = [
"https://www.google.com/",
"https://www.microsoft.com/",
"https://www.msdn.com/",
"https://www.stackoverflow.com/",
"https://www.yahoo.com/",
"https://www.bing.com/"
];
function checkIfTimeForVideo() {
var currentDateTimeStamp = new Date(),
currentTimestamp = currentDateTimeStamp.getHours() + ":" + currentDateTimeStamp.getMinutes();
if (timesToPlayVideos.indexOf(currentTimestamp) > -1) {
// Your code to play video here. Here is some non working example:
var arrayIndex = timesToPlayVideos.indexOf(currentTimestamp),
videoSrcToPlay = videoSources[arrayIndex];
// iframe used only for example purposes. replace with video tag and use:
// video.setAttribute("autoplay", "autoplay");
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", videoSrcToPlay);
document.body.appendChild(iframe);
} else {
// .innerHTML used only for example purposes.
document.body.innerHTML = "Please return at one of the specified times.";
}
}
window.setInterval(checkIfTimeForVideo, 60000);
我会使用 npm cron 和一个捆绑器。一个视频的示例:
const cron = require('cron');
const job = new cron.CronJob('00 00 11 * * *',
() => {
let video = document.createElement('video');
Object.assign(video, {src:"/assets/yourvideo.xxx",
autoplay:true,
controls:"controls"
});
document.body.appendChild(video);
},null, true, 'America/New_York'); // <== timezone
job.start();
然后创建一个捆绑包。例如:
browserify cronvideo.js -o public/javascripts/bundle.js
https://github.com/kelektiv/node-cron