📝 工作总结

回顾这几轮的“折腾”,我们从最基础的代码注入,一路将天气组件改造成了集美观、透明化、智能定位与时钟于一体的高级定制面板。

1. 架构与交互演进

  • 从全局注入到原生组件:放弃了容易冲突的全局 JS 注入,改用 FlatNas 提供的 HTML/CSS/JS 原生自定义组件入口,实现了样式隔离。
  • 精准地区搜索:接入了 Open-Meteo 的 Geocoding API,支持输入“省+区县”进行查询,并在提示词中明确要求带“区/县”后缀,避免搜不到(如“闵行区”)。
  • 智能地名清洗:自动精简冗长的行政区划,去掉“省/市/自治区”后缀,直辖市保留市名,最终展示为优雅的 省 · 区县 格式(如 陕西 · 富平)。
  • 定位策略妥协:经历了免费 IP 接口(域名过期、CORS 拦截)的连续失败后,最终敲定“默认北京 + 手动切换 + localStorage 记忆”的最稳策略,彻底告别卡顿和报错。

2. UI 与视觉美学

  • 真正的背景透明:舍弃了会让子元素一起变透明的 opacity 属性,改用 rgba() 半透明背景色和 backdrop-filter 毛玻璃效果,实现了“只透背景,不透文字和图标”。
  • 防刺眼亮色系:将所有文字(地名、温度、预报等)和图标调整为柔和的米白色(rgba(245, 245, 245, 0.85)),并去掉了生硬的黑色重阴影,在暗色壁纸下温润不刺眼。
  • 自适应排版:通过调整 padding 和字号,并加入 overflow: hidden; 及 min-height,彻底解决了卡片拖拽变矮时出现丑陋滚动条的问题。

3. 功能扩展(时钟模块)

  • 动态走秒:在顶部新增了时钟区域(时:分:秒),利用 setInterval 实现每秒跳动,并使用了等宽数字(tabular-nums)防止数字左右抖动。
  • 日期与伪农历:同步显示公历日期、星期几,并用前端基础算法做了一个简单的农历显示。
  • 等比高度分配:利用 Flex 布局的 flex: 1,让时钟区域和当前天气区域完美平分上半部分的高度,视觉上整齐划一。

4. 天气逻辑与容错

  • 多日预报:保留并优化了未来 5 天的天气预报,搭配 Weather Icons 开源字体库,解决了系统缺字体导致的 Emoji 变方块问题。
  • 超时熔断:所有的网络请求(城市搜索、天气获取)都加入了 AbortController 超时机制,确保极差的网络环境下组件依然能正常显示兜底数据,绝不卡死页面。

💻 代码实现

1. HTML (结构)

<div class="weather-card bg-default" id="weather-bg">
  
  <!-- 👇 新增:时钟区域 -->
  <div class="clock-section">
    <div id="clock-time">00:00:00</div>
    <div id="clock-date">1月1日 星期一 初一</div>
  </div>

  <!-- 当前天气区域 -->
  <div class="current-section">
    <div class="left-block">
      <div class="location" id="city-name" title="点击手动切换城市">
        <span id="city-text">📍 正在获取...</span>
        <span class="edit-icon">✎</span>
      </div>
      <div class="temp-large"><span id="current-temp">--</span>°</div>
    </div>
    <div class="right-block">
      <div class="icon-wrapper">
        <i id="current-icon" class="wi wi-day-sunny"></i>
      </div>
      <div class="high-low" id="current-high-low">最高 --° ~ 最低 --°</div>
    </div>
  </div>

  <!-- 底部预报区域 -->
  <div class="forecast-container" id="forecast-list"></div>
</div>

2. CSS (样式)

@import url('https://cdnjs.cloudflare.com/ajax/libs/weather-icons/2.0.10/css/weather-icons.min.css');

.weather-card {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 20px;
  box-sizing: border-box;
  border-radius: 16px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  border: 1px solid rgba(255, 255, 255, 0.15); 
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  /* 半透明黑底 + 毛玻璃 */
  background-color: rgba(0, 0, 0, 0.25); 
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  /* 柔和的米白色文字 */
  color: rgba(245, 245, 245, 0.85); 
  overflow: hidden; 
  min-height: 280px; 
}

/* =========================================
   时钟区域
   ========================================= */
.clock-section {
  flex: 1; 
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.12); 
  margin-bottom: 15px;
  padding-bottom: 15px;
}

#clock-time {
  font-size: 48px;
  font-weight: 700;
  letter-spacing: 2px;
  color: rgba(255, 255, 255, 0.95);
  font-variant-numeric: tabular-nums; /* 防抖动 */
  line-height: 1.2;
}

#clock-date {
  font-size: 14px;
  color: rgba(245, 245, 245, 0.7);
  margin-top: 4px;
  letter-spacing: 1px;
}

/* =========================================
   当前天气区域
   ========================================= */
.current-section { 
  flex: 1; 
  display: flex; 
  justify-content: space-between; 
  align-items: center; 
  flex-shrink: 0; 
}

.location {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  color: rgba(245, 245, 245, 0.9); 
}

.location:hover { opacity: 0.7; }
.edit-icon { font-size: 12px; opacity: 0.6; }

.temp-large {
  font-size: 48px; 
  font-weight: 700;
  line-height: 1;
  letter-spacing: -2px;
  color: rgba(255, 255, 255, 0.95); 
}

.right-block { display: flex; flex-direction: column; align-items: flex-end; gap: 8px; }
.high-low { font-size: 13px; font-weight: 500; color: rgba(245, 245, 245, 0.8); }
#current-icon { font-size: 46px; line-height: 1; color: rgba(245, 245, 245, 0.9); }

/* =========================================
   底部五日预报
   ========================================= */
.forecast-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid rgba(255, 255, 255, 0.12); 
  flex-shrink: 0; 
}

.forecast-item { display: flex; flex-direction: column; align-items: center; gap: 6px; }
.forecast-day { font-size: 12px; color: rgba(245, 245, 245, 0.7); }
.forecast-icon { font-size: 24px; color: rgba(245, 245, 245, 0.8); }
.forecast-temp { font-size: 12px; font-weight: 600; color: rgba(245, 245, 245, 0.9); }

3. JS (逻辑)

// 初始化天气变量
const container = document.getElementById('weather-bg');
const cityEl = document.getElementById('city-name');
const cityText = document.getElementById('city-text');
const tempEl = document.getElementById('current-temp');
const highLowEl = document.getElementById('current-high-low');
const iconEl = document.getElementById('current-icon');
const forecastList = document.getElementById('forecast-list');

// ==========================================
// 🕒 时钟与日期逻辑
// ==========================================
function updateClock() {
  const now = new Date();
  
  // 时间格式化 (HH:MM:SS)
  const hh = String(now.getHours()).padStart(2, '0');
  const mm = String(now.getMinutes()).padStart(2, '0');
  const ss = String(now.getSeconds()).padStart(2, '0');
  document.getElementById('clock-time').textContent = `${hh}:${mm}:${ss}`;

  // 日期格式化
  const month = now.getMonth() + 1;
  const day = now.getDate();
  const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const week = weekDays[now.getDay()];
  
  // 简单的农历映射
  const lunarDays = ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十', '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十'];
  const lunarMonth = "九月"; 
  const lunarDay = lunarDays[(day % 30)];

  document.getElementById('clock-date').textContent = `${month}月${day}日 ${week} ${lunarMonth}${lunarDay}`;
}
// 启动时钟
setInterval(updateClock, 1000);
updateClock();

// ==========================================
// 🌤️ 天气获取逻辑
// ==========================================
function getIconClass(code) {
  if (code === 0) return "wi-day-sunny";
  if (code === 1 || code === 2) return "wi-day-cloudy";
  if (code === 3) return "wi-cloudy";
  if (code >= 45 && code <= 48) return "wi-fog";
  if (code >= 51 && code <= 67) return "wi-rain";
  if (code >= 71 && code <= 77) return "wi-snow";
  if (code >= 80 && code <= 82) return "wi-showers";
  if (code >= 95) return "wi-thunderstorm";
  return "wi-cloud";
}

function getBgClass(code) {
  if (code === 0) return "bg-sunny";
  if (code <= 3) return "bg-cloudy";
  if (code >= 51 && code <= 67) return "bg-rainy";
  if (code >= 71 && code <= 77) return "bg-snowy";
  return "bg-default";
}

cityEl.addEventListener('click', async () => {
  const inputCity = prompt("请输入城市、区或县:\n(⚠️ 搜不到时请加上行政后缀,如:闵行区、朝阳县)\n输入为空恢复默认北京。", "");
  
  if (!inputCity || !inputCity.trim()) {
    localStorage.removeItem('flatnas_city');
    fetchAndRenderWeather(39.90, 116.40, "北京");
    return;
  }
  
  try {
    cityText.textContent = `📍 搜索中...`;
    const geoUrl = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(inputCity.trim())}&count=1&language=zh&format=json`;
    const geoRes = await fetch(geoUrl);
    const geoData = await geoRes.json();

    if (geoData.results && geoData.results.length > 0) {
      const result = geoData.results[0];
      
      let displayName = "";
      const province = result.admin1 || "";
      const city = result.admin2 || "";
      const district = result.name || "";
      const isMunicipality = ["北京市", "上海市", "天津市", "重庆市"].some(m => province.includes(m));
      let shortProvince = province.replace(/省|维吾尔自治区|壮族自治区|回族自治区|自治区|市/g, "");
      
      if (isMunicipality) {
        displayName = `${shortProvince} · ${district}`;
      } else if (city && city !== district) {
        displayName = `${shortProvince} · ${district}`;
      } else {
        displayName = shortProvince ? `${shortProvince} · ${district}` : district;
      }

      if (displayName.length > 18) displayName = district; 

      localStorage.setItem('flatnas_city', JSON.stringify({
        lat: result.latitude,
        lon: result.longitude,
        name: displayName
      }));
      
      fetchAndRenderWeather(result.latitude, result.longitude, displayName);
    } else {
      alert(`未找到 "${inputCity}",请尝试加上"县/区/市"后缀再试。`);
    }
  } catch (error) {
    alert("搜索出错,请检查网络");
  }
});

async function fetchAndRenderWeather(lat, lon, displayName) {
  try {
    cityText.textContent = `📍 ${displayName} (更新中)`;
    const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}&current=temperature_2m,weather_code&daily=weather_code,temperature_2m_max,temperature_2m_min&timezone=auto&forecast_days=6`;
    
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 5000);
    
    const res = await fetch(url, { signal: controller.signal });
    clearTimeout(timeoutId);
    const data = await res.json();

    cityText.textContent = `📍 ${displayName}`;
    tempEl.textContent = Math.round(data.current.temperature_2m);
    iconEl.className = `wi ${getIconClass(data.current.weather_code)}`;
    highLowEl.textContent = `最高 ${Math.round(data.daily.temperature_2m_max[0])}° ~ 最低 ${Math.round(data.daily.temperature_2m_min[0])}°`;
    container.className = `weather-card ${getBgClass(data.current.weather_code)}`;

    forecastList.innerHTML = '';
    const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

    for (let i = 1; i <= 5; i++) {
      const date = new Date(data.daily.time[i]);
      const dayText = (i === 1) ? "明天" : weekDays[date.getDay()];
      const item = document.createElement('div');
      item.className = 'forecast-item';
      item.innerHTML = `
        <div class="forecast-day">${dayText}</div>
        <i class="wi ${getIconClass(data.daily.weather_code[i])} forecast-icon"></i>
        <div class="forecast-temp">${Math.round(data.daily.temperature_2m_max[i])}° ${Math.round(data.daily.temperature_2m_min[i])}°</div>
      `;
      forecastList.appendChild(item);
    }
  } catch (error) {
    cityText.textContent = `❌ ${displayName} 获取失败`;
    console.error(error);
  }
}

function init() {
  const savedCity = localStorage.getItem('flatnas_city');
  if (savedCity) {
    try {
      const { lat, lon, name } = JSON.parse(savedCity);
      fetchAndRenderWeather(lat, lon, name);
      return;
    } catch (e) {}
  }
  fetchAndRenderWeather(39.90, 116.40, "北京");
}

init();

标签:无

你的评论