欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 练习小项目7:天气状态切换器

练习小项目7:天气状态切换器

2025/5/24 9:37:01 来源:https://blog.csdn.net/m0_67992720/article/details/148133404  浏览:    关键词:练习小项目7:天气状态切换器

🧠 项目目标:

点击按钮切换不同天气状态,背景或图标随之变化。

✨ 功能描述:

  • 显示当前天气(如:☀️ 晴天 / ☁️ 多云 / 🌧️ 雨天)

  • 点击“切换天气”按钮,每点击一次切换到下一种天气

  • 更换天气时,背景颜色或页面样式会变化

💡 技术点练习:

  • 数组索引循环

  • DOM 文本和样式修改

  • classList 切换

  • 对用户状态的可视反馈

 页面结构(HTML 参考):

<div class="container"><h2 id="weatherText">☀️ 晴天</h2><button id="changeBtn">切换天气</button>
</div>

 实践代码如下: 

JS: 

const weatherText = document.getElementById('weatherText')
const changeBtn = document.getElementById('changeBtn')const weatherData = [{ icon: "☀️", text: "晴天", class: "sunny" },{ icon: "☁️", text: "多云", class: "cloudy" },{ icon: "🌧️", text: "雨天", class: "rainy" }
]let i = 0
const updateWeather = (index) => {// 更新文本weatherText.textContent = `${weatherData[index].icon} ${weatherData[index].text}`// 移除所有旧的 classweatherData.forEach(weather => {document.body.classList.remove(weather.class)})// 添加新的 classdocument.body.classList.add(weatherData[index].class)// 更新全局索引 ii = index
}
changeBtn.addEventListener('click', () => {// 每次调用时,传入下一个索引updateWeather((i + 1) % weatherData.length)
})// 初始设置
updateWeather(0)

 CSS:

 body {transition: background-color 0.3s;font-family: sans-serif;text-align: center;padding-top: 50px;}.sunny {background-color: #ffe066;color: #333;}.cloudy {background-color: #d0d0d0;color: #333;}.rainy {background-color: #7f8fa6;color: white;}button {margin-top: 20px;padding: 10px 20px;}

页面效果展示 : 

 

额外知识记录:

(i + 1) % weatherData.length的理解

这是循环索引的技巧:

  • i 是当前索引

  • 加 1 后对总长度取余,可以在数组中循环切换,比如 0 → 1 → 2 → 0...

✅ 清空样式的方式

weatherData.forEach(weather => {document.body.classList.remove(weather.class)
})

虽然每次都移除所有 class,看起来“重复”,但这种方式:

  • 简单清晰 

  • 不需要判断当前状态 

  • 性能上没问题(浏览器对 classList.remove 做了优化)

这是小项目中推荐使用的方式

✅ 如果在 updateWeather(index) 函数里不加i=index会怎么样?

会导致 全局变量 i 不能正确更新当前显示的天气索引,从而影响下一次点击时计算的“下一个天气”。

具体表现是:

  • 第一次点击按钮时,nextIndex = (i + 1) % weatherData.length,假设 i 是 0,nextIndex 就是 1。

  • 调用 updateWeather(1) 显示了第2个天气,但如果没有 i = index,全局变量 i 依然是 0。

  • 下一次点击时,nextIndex 还是 (0 + 1) % length,还是 1,页面显示的不会切换到第3个天气,永远停留在第2个。

  • 也就是说,点击按钮后显示会切换,但内部“记录当前天气索引”的变量没有更新,导致后续点击计算下一状态出错,循环无法正常进行。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词