小时天气预报
逐日天气预报
javascript
// 获取清远24小时天气预报数据
let weatherData = await fetch("https://api.weatherbit.io/v2.0/forecast/daily?city=Qingyuan,China&key={{weatherbit_api_key}}&hours=24").then(res => res.json()).then(data => data.data[0]);// 设置今日天气信息
document.getElementById("temperature").textContent = weatherData.temp.toFixed(1) + "°C";
document.getElementById("weather-condition").textContent = weatherData.weather.description;
document.getElementById("humidity").textContent = weatherData.rh + "%";
document.getElementById("wind-speed").textContent = weatherData.wind_spd.toFixed(1) + "米/秒";// 设置小时天气预报
let hourlyForecastList = document.getElementById("hourly-forecast-list");
for (let i = 1; i < 24; i += 3) {let hourlyForecastItem = document.createElement("li");let hourlyForecastTime = document.createElement("span");hourlyForecastTime.textContent = new Date(weatherData.ts[i] 1000).toLocaleTimeString("zh-CN");let hourlyForecastIcon = document.createElement("img");hourlyForecastIcon.src = `${weatherData.weather[i].icon}.png`;hourlyForecastIcon.alt = weatherData.weather[i].description;let hourlyForecastTemp = document.createElement("span");hourlyForecastTemp.textContent = weatherData.temp[i].toFixed(1) + "°C";hourlyForecastItem.appendChild(hourlyForecastTime);hourlyForecastItem.appendChild(hourlyForecastIcon);hourlyForecastItem.appendChild(hourlyForecastTemp);hourlyForecastList.appendChild(hourlyForecastItem);
}// 设置逐日天气预报
let dailyForecastList = document.getElementById("daily-forecast-list");
for (let i = 1; i < 7; i++) {let dailyForecastItem = document.createElement("li");let dailyForecastDate = document.createElement("span");dailyForecastDate.textContent = new Date(weatherData.ts[i 24] 1000).toLocaleDateString("zh-CN");let dailyForecastIcon = document.createElement("img");dailyForecastIcon.src = `${weatherData.weather[i 24].icon}.png`;dailyForecastIcon.alt = weatherData.weather[i 24].description;let dailyForecastTemp = document.createElement("span");dailyForecastTemp.textContent = `${weatherData.min_temp[i 24].toFixed(1)}°C ~ ${weatherData.max_temp[i 24].toFixed(1)}°C`;dailyForecastItem.appendChild(dailyForecastDate);dailyForecastItem.appendChild(dailyForecastIcon);dailyForecastItem.appendChild(dailyForecastTemp);dailyForecastList.appendChild(dailyForecastItem);
}