天津天气查询7天预报最新消息今天 (天津天气查询30天)

天津桑拿 05-14 阅读:14 评论:0

今天的天气

°C
天津天气查询7天预报最新消息今天 (天津天气查询30天)

7天天气预报

JavaScript 代码(script.js): javascript const weatherWidget = document.getElementById("weather-widget"); const currentWeather = document.getElementById("current-weather"); const tempValue = document.getElementById("temp-value"); const tempUnit = document.getElementById("temp-unit"); const weatherIcon = document.getElementById("icon"); const description = document.getElementById("description"); const forecast = document.getElementById("forecast"); const forecastList = document.getElementById("forecast-list");const API_KEY = "API_KEY_HERE"; // 替换为你的 API 密钥const getWeatherData = async(city, days) => {const res = await fetch(`${city}&appid=${API_KEY}&units=metric&cnt=${days}`);return await res.json(); };const displayWeatherData = (data) => {// 当前天气tempValue.textContent = data.list[0].main.temp;weatherIcon.src = `${data.list[0].weather[0].icon}@2x.png`;description.textContent = data.list[0].weather[0].description;// 7 天预报for (let i = 1; i < 8; i++) {// 创建列表项const forecastItem = document.createElement("li");forecastItem.classList.add("forecast-item");// 日期const date = new Date(data.list[i].dt 1000);const dateElement = document.createElement("span");dateElement.classList.add("date");dateElement.textContent = `${date.getDate()}/${date.getMonth() + 1}`;forecastItem.appendChild(dateElement);// 天气图标const iconElement = document.createElement("div");iconElement.classList.add("icon-forecast");const iconSrc = `${data.list[i].weather[0].icon}.png`;const iconImg = document.createElement("img");iconImg.src = iconSrc;iconElement.appendChild(iconImg);forecastItem.appendChild(iconElement);// 最高温和最低温const tempElement = document.createElement("div");tempElement.classList.add("temp-forecast");const highTemp = document.createElement("span");highTemp.classList.add("high");highTemp.textContent = `${data.list[i].main.temp_max}°C`;const lowTemp = document.createElement("span");lowTemp.classList.add("low");lowTemp.textContent = `${data.list[i].main.temp_min}°C`;tempElement.appendChild(highTemp);tempElement.appendChild(lowTemp);forecastItem.appendChild(tempElement);// 天气描述const descriptionElement = document.createElement("div");descriptionElement.classList.add("description-forecast");const descriptionText = document.createElement("p");descriptionText.textContent = data.list[i].weather[0].description;descriptionElement.appendChild(descriptionText);forecastItem.appendChild(descriptionElement);// 将列表项添加到列表中forecastList.appendChild(forecastItem);} };const init = async () => {const weatherData = await getWeatherData("天津", 8);displayWeatherData(weatherData); };init();
版权声明

本文仅代表作者观点,不代表天津桑拿立场。
本文系作者授权发表,未经许可,不得转载。

分享:

扫一扫在手机阅读、分享本文