
本文详解如何通过调用天气 api 获取实时温度数据,并基于温度数值范围(如 ≤10°c、11–19°c、≥20°c)自动设置 body 背景色,包含完整异步请求示例、常见错误分析与实用注意事项。
在前端开发中,根据动态数据(如实时天气温度)改变页面视觉效果是一种常见且实用的交互设计。但初学者常因数据获取时机、API 响应结构或 DOM 访问方式不当而遇到 undefined 错误——正如问题中所示:data.main.temp 报错,本质是未正确解析 API 返回的 JSON 数据结构,或在数据未加载完成时就尝试读取。
以下是一个健壮、可运行的实现方案,使用免费的 Open-Meteo API(无需 API Key),并适配摄氏单位:
async function colorChange() {
try {
// 请求 Denver(纬度39.7392,经度-104.9847)当日最高气温
const response = await fetch(
"https://api.open-meteo.com/v1/forecast?latitude=39.7392&longitude=-104.9847&daily=temperature_2m_max&timezone=GMT&forecast_days=1"
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const tempColor = data.daily.temperature_2m_max[0]; // ✅ 正确路径:数组首项即当日最高温
console.log("当前最高气温:", tempColor, "°C");
// 根据温度区间设置背景色
if (tempColor <= 10) {
document.body.style.backgroundColor = "lightgrey";
} else if (tempColor >= 11 && tempColor < 20) {
document.body.style.backgroundColor = "lightblue";
} else {
document.body.style.backgroundColor = "lightcoral";
}
// 可选:将温度显示在页面上便于调试
document.querySelector("div#temp-display")?.textContent =
`?️ ${tempColor}°C`;
} catch (err) {
console.error("获取温度失败:", err);
document.body.style.backgroundColor = "whitesmoke"; // 降级默认色
}
}
// 页面加载完成后执行
document.addEventListener("DOMContentLoaded", colorChange);配套 HTML 与基础样式(确保 DOM 存在):
Temp goes here
#temp-display {
padding: 16px;
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
text-align: center;
margin: 20px auto;
max-width: 300px;
}? 关键要点说明:
立即学习“Java免费学习笔记(深入)”;
- ✅ 结构匹配优先:OpenWeatherMap 的 data.main.temp 与 Open-Meteo 的 data.daily.temperature_2m_max[0] 结构不同,务必根据所选 API 文档确认字段路径;
- ✅ 异步必须 await:fetch() 返回 Promise,需用 await 等待解析完成,否则 data 为 undefined;
- ✅ 错误处理不可少:网络失败、跨域限制、API 限流等均可能导致请求中断,try...catch 是生产环境必备;
- ⚠️ 避免硬编码 DOM 查询:原问题中 document.querySelector(data.main.temp).value 逻辑错误——data.main.temp 是数字,不是 CSS 选择器;应先获取数据,再操作 DOM;
- ? 单位注意:Open-Meteo 默认返回摄氏度;若使用 OpenWeatherMap,请务必添加 &units=metric 参数,否则默认为开尔文(K)。
? 进阶建议:
- 将颜色逻辑抽离为独立函数(如 getBgColorByTemp(temp)),提升可测试性;
- 添加平滑过渡:document.body.style.transition = 'background-color 0.5s ease';
- 支持用户定位:用 navigator.geolocation 替代固定坐标,实现本地化天气响应。
掌握这一模式后,你不仅能实现温度驱动的背景变色,还可轻松扩展至湿度、空气质量、甚至自定义业务指标(如订单量、服务器负载)的可视化反馈。










