分享一个使用高德 API 获取并在顶栏显示天气的 js。每 20 分钟自动从高德 API 拉取一次天气情况,手动点击顶栏天气,实时拉取一次天气情况。
感谢 carlreel 的帖子提供高德 API 的获取方法:通过 QueryView 插件和高德 API 获取天气信息 - 链滴
还要感谢 wilsons 大佬提供的顶栏显示天气的方法:[js] 思源左侧空白区域显示心灵毒鸡汤或倒计时和顶部显示天气 - 链滴
本 js 是在以上两个帖子的基础上,使用 AI 生成的,实现效果如上图。需要使用自己的高德 apikey 和城市代码 citycode。
(function() { // 配置参数(需要用户自行修改) const apiKey = '替换为自己从高德API申请的key'; const cityCode = '替换为自己搜索或问AI得到的自己的城市代码'; const refreshInterval = 20 * 60 * 1000; // 20分钟更新间隔 const showWeather = true; // 天气现象与Emoji映射表 const weatherEmoji = { '晴': '🌟', '雨': '🌧️', '雪': '❄️', '阴': '☁️', '云': '⛅', '雾': '🌫️', '霾': '😷', '雷': '⛈️', '风': '🌪️', '热': '🔥', '冷': '🥶' }; // 时间格式化函数 function formatAPIDateTime(apiDateTime) { const [datePart, timePart] = apiDateTime.split(' '); return `${timePart}`; } function formatLocalDateTime(date) { const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0'); return `${hours}:${minutes}:${seconds}`; } async function showTodayWeather() { // 清除所有历史天气元素 document.querySelectorAll('.today-weather').forEach(el => el.remove()); if (!showWeather) return; try { // 同时获取实时和预测天气数据 const [baseResponse, allResponse] = await Promise.all([ fetch(`https://restapi.amap.com/v3/weather/weatherInfo?key=${apiKey}&city=${cityCode}&extensions=base`), fetch(`https://restapi.amap.com/v3/weather/weatherInfo?key=${apiKey}&city=${cityCode}&extensions=all`) ]); if (!baseResponse.ok || !allResponse.ok) throw new Error("天气请求失败"); const baseData = await baseResponse.json(); const allData = await allResponse.json(); const weatherData = baseData.lives[0]; const forecastData = allData.forecasts[0]; // 智能匹配天气图标 const weatherIcon = Object.keys(weatherEmoji).find(key => weatherData.weather.includes(key) ) || '🌍'; // 处理预测温度显示 const forecastTips = forecastData.casts.map(cast => { const date = new Date(cast.date); const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]; return `📅 ${date.getMonth()+1}/${date.getDate()} ${weekdays[date.getDay()]}:${cast.dayweather},${cast.nighttemp}°C ~ ${cast.daytemp}°C,${cast.daywind}风${cast.daypower}级`; }).join('\n'); await createWeatherElement(ellipsis => { // 构造主显示信息 const mainInfo = [ `|| ${weatherEmoji[weatherIcon]} ${weatherData.weather}`, `🌡${weatherData.temperature}°C`, `🍃${weatherData.windpower}级` ].join(' '); // 构造悬浮提示 const tooltip = [ `📍 ${weatherData.province}省${weatherData.city}`, `🧭 风向: ${weatherData.winddirection}风`, `💧 湿度: ${weatherData.humidity}%`, `🕒 高德更新: ${formatAPIDateTime(weatherData.reporttime)}`, `🕒 本地请求: ${formatLocalDateTime(new Date())}`, '\n天气预测:', forecastTips ].join('\n'); return { content: mainInfo, tooltip }; }); } catch (error) { console.error('天气获取失败:', error); await createWeatherElement(() => ({ content: '⚠️ 天气获取失败', tooltip: `错误信息:${error.message}\n最后尝试时间:${formatLocalDateTime(new Date())}` })); } } async function createWeatherElement(contentGenerator) { await whenElementExist('#toolbar .fn__ellipsis').then(ellipsis => { // 创建统一容器 const weatherDiv = document.createElement('div'); weatherDiv.className = 'today-weather'; weatherDiv.style.cssText = ` position: relative; margin-right: 15px; color: var(--b3-toolbar-color); font-size: 14px; cursor: pointer; `; // 生成内容 const { content, tooltip } = contentGenerator(ellipsis); // 创建内容容器 const contentDiv = document.createElement('div'); contentDiv.title = tooltip; contentDiv.style.display = 'flex'; contentDiv.style.alignItems = 'center'; contentDiv.style.gap = '5px'; contentDiv.style.whiteSpace = 'nowrap'; contentDiv.textContent = content; // 添加点击刷新功能 contentDiv.addEventListener('click', function() { this.style.whiteSpace = this.style.whiteSpace === 'nowrap' ? 'pre' : 'nowrap'; showTodayWeather(); }); weatherDiv.appendChild(contentDiv); ellipsis.before(weatherDiv); }); } function whenElementExist(selector) { return new Promise(resolve => { const check = () => { const el = document.querySelector(selector); el ? resolve(el) : requestAnimationFrame(check); }; check(); }); } // 初始化 showTodayWeather(); setInterval(showTodayWeather, refreshInterval); })();
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于