javascript - 带有基于小时的灵活计时器的 Java Script 横幅
问题描述
我想制作一个简短的脚本来在特定时间段内显示横幅。像这样:从上午 9:30 开始。到上午 10 点。从上午 11 点开始显示横幅 1。到凌晨 12 点 15 分。从晚上 8:10 开始显示横幅 2。到晚上 10 点。显示横幅 3 等等。
我弥补了这一点,但它不能以正确的方式工作。
请帮助我理解并解决问题。我怎样才能添加分钟?似乎它只需要几个小时。
特别感谢
<head>
<script>
var current= new Date()
var day_night=current.getHours()
if (day_night<=2){
document.write("<img src='1.png' style='width: 100%; max-width: 600px; height: auto;'>");
}
else if (day_night<=3){
document.write("<img src='3.jpg' style='width: 100%; max-width: 600px; height: auto;'>");
}
else if (day_night<=4){
document.write("<img src='4.png' style='width: 100%; max-width: 600px; height: auto;'>");
}
else{
document.write("<img src='night.gif' style='width: 100%; max-width: 600px; height: auto;'>");
}
</script>
</head>
<body>
</body> ```
解决方案
你可以这样尝试
const timetable = [
{ banner: '<img src="night.gif" style="width: 100%; max-width: 600px; height: auto;">', fromTime: '10:00', toTime: '11:30' },
{ banner: '<img src="1.gif" style="width: 100%; max-width: 600px; height: auto;">', fromTime: '12:00', toTime: '12:15' },
];
function getCurrentBanner() {
const date = new Date();
const hour = date.getHours();
const minutes = date.getMinutes();
let currentBanner = null;
timetable.forEach(item => {
const [fromHour, fromMinutes] = item.fromTime.split(':');
const [toHour, toMinutes] = item.toTime.split(':');
if (hour >= Number(fromHour) && minutes >= Number(fromMinutes) && hour <= Number(toHour) && minutes <= Number(toMinutes)) {
currentBanner = item.banner;
return;
}
})
return currentBanner;
}
const b = getCurrentBanner();
推荐阅读
- java - 有没有办法将创建的配置(节点和数据)导出到 zookeeper 中的普通属性?
- spring - Spring Boot:H2 实际上并未从数据库中检索
- c++ - 字符串 v 等于左右旋转
- raspberry-pi4 - 如何在 Raspberry Pi/Windows 10 中查找和输入域名?
- sql - SQL Query 对单独查询的结果进行分类
- git - 从一组存储库创建单个存储库
- python - 如何从字典python中的while循环更新值(列表形式)
- java - 离开活动时如何停止我的应用程序的振动?
- javascript - React - 从子组件更新状态不起作用
- python - 如何在 Pyscripter 中打印熊猫数据框的表格?