纯前端实现在网站上挂一个漂亮的天气标签。


天气来源
使用openweather提供的免费api,需注册帐号,生成api-key。
数据获取方式:
https://api.openweathermap.org/data/2.5/weather?q=beijing&appid=xxxxxxxx&units=metric&lang=zh_cn
或
https://api.openweathermap.org/data/2.5/weather?lat=39.91&lon=116.40&appid=xxxxxxxx&units=metric&lang=zh_cn
返回:
{"coord":{"lon":116.3972,"lat":39.9075},"weather":[{"id":800,"main":"Clear","description":"晴","icon":"01n"}],"base":"stations","main":{"temp":12.94,"feels_like":10.66,"temp_min":12.94,"temp_max":12.94,"pressure":1015,"humidity":14,"sea_level":1015,"grnd_level":1010},"visibility":10000,"wind":{"speed":2.96,"deg":297,"gust":8.78},"clouds":{"all":0},"dt":1745764328,"sys":{"type":1,"id":9609,"country":"CN","sunrise":1745702400,"sunset":1745751833},"timezone":28800,"id":1816670,"name":"Beijing","cod":200}
代码
徽章显示的地方:
<img id="weather-badge" src="">
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| <script> // 配置 const LAT = 39.93; //经纬度 const LON = 119.59; const API_KEY = "xxxxxxxx"; // 替换为你的API密钥 const CITY_NAME = "今日天气"; // 自定义显示名称
async function updateWeatherBadge() { try { // 1. 获取天气数据 const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${LAT}&lon=${LON}&appid=${API_KEY}&units=metric&lang=zh_cn`; const response = await fetch(apiUrl); const data = await response.json(); const temp = Math.round(data.main.temp); const description = data.weather[0].description; // 2. 根据温度选择颜色 let color; if (temp < 0) color = "lightblue"; else if (temp < 10) color = "blue"; else if (temp < 20) color = "green"; else if (temp < 30) color = "orange"; else color = "red"; // 3. 生成 Shields.io 徽章 URL const badgeUrl = `https://img.shields.io/badge/${encodeURIComponent(CITY_NAME)}-${temp}°C_${encodeURIComponent(description)}-${color}.svg`; // 4. 更新徽章 document.getElementById("weather-badge").src = badgeUrl; } catch (error) { console.error("获取天气失败:", error); // 显示错误徽章 document.getElementById("weather-badge").src = "https://img.shields.io/badge/天气-加载失败-red.svg"; } }
// 初始加载 + 每30分钟更新一次 updateWeatherBadge(); setInterval(updateWeatherBadge, 30 * 60 * 1000); </script>
|