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

发布于:2025-05-25 ⋅ 阅读:(17) ⋅ 点赞:(0)

🧠 项目目标:

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

✨ 功能描述:

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

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

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

💡 技术点练习:

  • 数组索引循环

  • 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}`
    // 移除所有旧的 class
    weatherData.forEach(weather => {
        document.body.classList.remove(weather.class)
    })

    // 添加新的 class
    document.body.classList.add(weatherData[index].class)

    // 更新全局索引 i
    i = 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个。

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


网站公告

今日签到

点亮在社区的每一天
去签到