首页 > 解决方案 > 带有基于小时的灵活计时器的 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> ```

标签: javascripthtmltimer

解决方案


你可以这样尝试

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();

推荐阅读