本文详解如何通过调用天气 api 获取实时温度数据,并基于温度数值范围(如 ≤10°c、11–19°c、≥20°c)自动设置 body 背景色,包含完整异步请求示例、常见错误分析与实用注意事项。
在前端开发中,根据动态数据(如实时天气温度)改变页面视觉效果是一种常见且实用的交互设计。但初学者常因数据获取时机、API 响应结构或 DOM 访问方式不当而遇

以下是一个健壮、可运行的实现方案,使用免费的 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;
}? 关键要点说明:
? 进阶建议:
掌握这一模式后,你不仅能实现温度驱动的背景变色,还可轻松扩展至湿度、空气质量、甚至自定义业务指标(如订单量、服务器负载)的可视化反馈。
来电咨询