You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现网页背景每日切换、循环使用4张预设背景图的功能

背景图每日循环切换实现方案

仅需增加少量原生JavaScript代码即可实现,无需引入其他复杂技术栈。


步骤1:修改原有CSS

移除你现有CSS中写死的背景图地址,其余属性保持不变:

.main-section .main-division {
  /* 替换原来的background行,移除固定的图片url */
  background: no-repeat center;
  background-size: cover;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  -ms-background-size: cover;
  position: relative;
  z-index: 0;
  min-height: 100vh;
  align-items: center;
  display: grid;
  height:auto;
  max-width: 100%;
}

步骤2:在HTML中插入JS代码

将以下代码放在你的HTML文件的</body>标签之前即可:

<script>
// 定义4张背景图的路径,可根据你实际的文件存放位置修改
const bgImages = [
  '../images/background-1.jpg',
  '../images/background-2.jpg',
  '../images/background-3.jpg',
  '../images/background-4.jpg'
]
// 获取当天日期的日数,比如1号返回1,15号返回15
const dayOfMonth = new Date().getDate()
// 对4取模得到0-3的索引,实现4张图循环
const bgIndex = dayOfMonth % 4
// 选中目标元素设置背景图
const targetEle = document.querySelector('.main-division')
targetEle.style.backgroundImage = `url(${bgImages[bgIndex]})`
</script>

逻辑说明

  • 按自然日自动切换:同一天内多次刷新页面都会显示同一张背景图,到次日自动切换到下一张
  • 自动循环:4张图轮播完成后会自动回到第一张重新循环,无需额外配置
  • 如果你的图片存放路径和示例不一致,直接修改bgImages数组内的路径即可生效

内容的提问来源于stack exchange,提问作者Darknicks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 08:36:01