萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 每日自動切換圖片:基於日期的動態圖片顯示實作

應用場景

  • 每日一圖 / 每日一句網站首頁
  • 輪播廣告按日期自動切換
  • 日曆應用、打卡簽到頁面
  • 無需後端、零維護成本的動態內容

核心原理

利用 new Date().getDate() 獲取當月日期 (1-31),拼接成圖片檔名 (如 1.jpg, 15.jpg),自動切換顯示。

完整實作 (現代化增強版)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>每日自動切換圖片</title>
  <style>
    .container { max-width: 600px; margin: 50px auto; text-align: center; font-family: sans-serif; }
    .daily-image { max-width: 100%; height: auto; border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,0.12); transition: opacity 0.5s ease; }
    .loading { color: #999; font-style: italic; }
    .meta { margin-top: 16px; color: #666; font-size: 14px; }
    .nav { margin-top: 20px; display: flex; justify-content: center; gap: 10px; }
    button { padding: 10px 20px; background: #1976d2; color: white; border: none; border-radius: 6px; cursor: pointer; }
    button:disabled { background: #ccc; cursor: not-allowed; }
  </style>
</head>
<body>
  <div class="container">
    <h1>📅 每日一圖</h1>
    <div class="meta">今天是: {
      $img.css('opacity', 1);
      $('#imgLink').attr('href', url);
    }).on('error', () => {
      $img.attr('src', CONFIG.fallback).css('opacity', 0.7);
      $('#imgLink').attr('href', '#');
      log(`圖片載入失敗: ${url},使用備用圖`);
    }).css('opacity', 0.5).attr('src', url);
    
    // 按鈕狀態
    $('#btnPrev').prop('disabled', day === 1);
    $('#btnNext').prop('disabled', day === CONFIG.totalDays);
  }

  function log(msg) {
    console.log(`[${new Date().toLocaleTimeString()}] ${msg}`);
  }

  // 事件綁定
  $('#btnPrev').on('click', () => {
    currentDate.setDate(currentDate.getDate() - 1);
    updateDisplay();
  });
  $('#btnNext').on('click', () => {
    currentDate.setDate(currentDate.getDate() + 1);
    updateDisplay();
  });
  $('#btnToday').on('click', () => {
    currentDate = new Date();
    updateDisplay();
  });

  // 初始化
  updateDisplay();
  </script>
</body>
</html>

進階擴充方案

1. 月份感知:自動計算當月天數

function getDaysInMonth(year, month) {
  // month: 0-11
  return new Date(year, month + 1, 0).getDate();
}

const today = new Date();
const daysInMonth = getDaysInMonth(today.getFullYear(), today.getMonth());
CONFIG.totalDays = daysInMonth;

2. 圖片預載入 (避免切換閃爍)

function preloadImages(urls) {
  urls.forEach(url => {
    const img = new Image();
    img.src = url;
  });
}

// 預載入前後幾天
const preloadUrls = [];
for (let i = -2; i <= 2; i++) {
  const d = new Date(currentDate);
  d.setDate(d.getDate() + i);
  if (d.getDate() >= 1 && d.getDate() <= CONFIG.totalDays) {
    preloadUrls.push(getImageUrl(d));
  }
}
preloadImages(preloadUrls);

3. 支援雲端圖床 / CDN 路徑

// 例如:https://cdn.example.com/daily/2024/01/15.jpg
const CONFIG = {
  basePath: 'https://cdn.example.com/daily/',
  ext: '.jpg',
  // 動態生成完整路徑
  getUrl: (date) => {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${CONFIG.basePath}${y}/${m}/${d}${CONFIG.ext}`;
  }
};

4. 結合 localStorage 記住用戶最後查看日期

// 載入時恢復
const saved = localStorage.getItem('lastViewedDate');
if (saved) currentDate = new Date(saved);

// 切換時保存
function updateDisplay() {
  // ...
  localStorage.setItem('lastViewedDate', currentDate.toISOString());
}

避坑指南

⚠ 常見問題:
  • 路徑錯誤:相對路徑基於 HTML 頁面位置,而非 JS 檔案位置
  • 大小寫敏感:Linux 伺服器 1.JPG ≠ 1.jpg
  • 跨域限制:file:// 協議下無法載入圖片,需用本地伺服器 (Live Server, http-server)
  • 快取問題:同檔名內容更新需加版本號 ?v=20240115 或設定 Cache-Control

總結

「每日一圖」是零後端成本的動態內容方案。核心只需 3 行代碼:

const day = new Date().getDate();
document.getElementById('img').src = `images/${day}.jpg`;
document.getElementById('link').href = `images/${day}.jpg`;

配合錯誤處理、預載入、月份感知、CDN 支援,即可構建生產級的每日圖片展示功能。

copyright © 萬盛學電腦網 all rights reserved