🧠 項目目標:
點擊按鈕切換不同天氣狀態,背景或圖標隨之變化。
? 功能描述:
-
顯示當前天氣(如:?? 晴天 / ?? 多云 / 🌧? 雨天)
-
點擊“切換天氣”按鈕,每點擊一次切換到下一種天氣
-
更換天氣時,背景顏色或頁面樣式會變化
💡 技術點練習:
-
數組索引循環
-
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個。 -
也就是說,點擊按鈕后顯示會切換,但內部“記錄當前天氣索引”的變量沒有更新,導致后續點擊計算下一狀態出錯,循環無法正常進行。