推荐用 OpenWeatherMap API(需注册获取 appid、用城市 ID 而非名称、units=metric 避免开尔文换算),HTTPS 下 fetch 请求,加加载状态与容错处理(如可选链),本地须用 HTTP 服务预览,结构样式分离,50 行内可实现。

直接用第三方天气 API 嵌入最可靠
浏览器里没法直接“插入天气插件”——没有标准的 <weather> 标签,所有所谓“插件”本质都是 JS 脚本调用 API 渲染 DOM。推荐用 OpenWeatherMap(免费额度够个人站用),它返回 JSON,前端可控性强,不会突然失效或强塞广告。
关键点:必须走 HTTPS 请求(fetch 会拒绝 HTTP 页面上的混合内容),且需注册获取 appid(免费账户在 https://www.php.cn/link/055bac208ceea65244da625816501e94)。
- 把
appid存在 JS 里(别暴露在公开仓库); - 城市 ID 比城市名更稳定(避免重名、拼音错误),查 ID 用:
https://api.openweathermap.org/geo/1.0/direct?q=Beijing&limit=1&appid=YOUR_KEY; - 接口返回温度是开尔文,记得减
273.15; - 加个简单加载状态(比如显示
Loading…),避免白屏卡顿感。
用 fetch + innerHTML 最简实现
不用框架、不引库,50 行内搞定。重点不是“怎么写”,而是“怎么不出错”:
const cityId = '1816670'; // 北京 ID
const appId = 'your_appid_here';
const url = `https://api.openweathermap.org/data/2.5/weather?id=${cityId}&appid=${appId}&units=metric`;
fetch(url)
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then(data => {
const temp = Math.round(data.main.temp);
const desc = data.weather[0].description;
const el = document.getElementById('weather');
el.innerHTML = `<strong>${temp}°C</strong> ${desc}`;
})
.catch(err => {
console.error('天气加载失败:', err);
document.getElementById('weather').textContent = '暂无数据';
});
注意:data.weather[0] 必须加索引,因为 weather 是数组(即使只有一项);units=metric 才返回摄氏度,漏写默认是开尔文。
立即学习“前端免费学习笔记(深入)”;
避免跨域和缓存导致的“偶尔失效”
本地双击打开 index.html(即 file:// 协议)时,fetch 会直接被浏览器拦截——这是安全限制,不是代码错。必须用本地服务预览:
- VS Code 装
Live Server插件,右键启动; - 命令行用
npx http-server(需先npm install -g http-server); - Chrome 启动时加参数
--unsafely-treat-insecure-origin-as-secure="file://"(仅临时调试,不推荐)。
另外,API 默认不带缓存头,但某些代理或 PWA 会意外缓存旧响应。可在 URL 末尾加时间戳绕过:&t=${Date.now()}(仅调试用,上线建议配合理想的 Cache-Control)。
样式和容错要写在 JS 外部
别在 JS 里拼大段 HTML 字符串,尤其带样式。把结构和样式分离:
<div id="weather" class="weather-widget"></div>
然后用 CSS 控制外观:
.weather-widget {
font-size: 14px;
color: #333;
}
.weather-widget strong {
font-size: 18px;
color: #e74c3c;
}
这样改文字大小、颜色、加图标都方便。更重要的是:如果 API 返回字段缺失(比如 data.weather 是空数组),JS 里应有兜底逻辑(如 data.weather?.[0]?.description || '未知'),否则页面可能报 Cannot read property 'description' of undefined 错误。
真正麻烦的从来不是“怎么显示天气”,而是“网络失败、字段变更、本地协议限制、缓存污染”这些边缘情况——它们会在你发版后某个周二下午三点集体爆发。


















