如何根据时间网页中显示不同的图片?JavaScript

济南云服务器 2026年6月2日09:55:58JavaScript如何根据时间网页中显示不同的图片?JavaScript已关闭评论61阅读模式

我们在制作网页时,可以根据时间,比如,上午,下午,晚上在网页中显示不同的图片,那么,这个功能具体该如何实现呢?接下来,济南网站建设小编就来为大家分享一个小案例,有需要的朋友可以过来参考一下。

关键代码:

 

<script>
        // 三组在线示例图
        let imgArr = {
            morning:"/id/1039/450/300",
            afternoon:"/id/1036/450/300",
            night:"/id/1048/450/300"
        }
        let img = document.getElementById('pic');
        let tip = document.getElementById('tip');
        let now = new Date();
        let h = now.getHours();

        if(h>=6 && h<12){
            img.src = imgArr.morning;
            tip.innerText = `当前${h}点,早上好,展示晨间风景`;
        }else if(h>=12 && h<18){
            img.src = imgArr.afternoon;
            tip.innerText = `当前${h}点,午后时光,展示白日风景`;
        }else{
            img.src = imgArr.night;
            tip.innerText = `当前${h}点,夜幕降临,展示夜景`;
        }
    </script>

济南云服务器
  • 本文由 发表于 2026年6月2日09:55:58
  • 转载请务必保留本文链接:http://news.hcsw666.com/2792