萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 + CSS3 打造創意 404 頁面:從 SVG 動畫到交互式失落體驗

為什麼 404 頁面值得精心設計?

404 是用戶旅程中的「斷點」,處理得當能:

  • 降低跳出率:提供清晰導航回主站/搜尋/網站地圖
  • 品牌人格化:幽默、插畫、互動展現品牌調性
  • 收集情報:記錄 404 來源 URL、Referrer、User Agent,修復死連結
  • 轉化機會:推薦熱門內容、引導訂閱、提供優惠碼

創意 404 核心構想:「迷路的太空人」

主視覺:SVG 繪製的太空人漂浮在星空,氧氣管斷裂、指南針失靈。滑鼠移動視差效果、點擊觸發粒子爆炸、鍵盤方向鍵控制太空人漂浮。

完整實作代碼

HTML 結構(語義化、無障礙優先)

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>404 - 頁面走失了 | 星際導航</title>
  <meta name="robots" content="noindex">
  <link rel="stylesheet" href="404.css">
</head>
<body>
  <main class="error-404" role="main">
    <div class="space-scene" id="spaceScene">
      <svg class="astronaut" viewBox="0 0 200 300" aria-hidden="true">
        <!-- 太空人 SVG 路徑(省略,見下方完整檔案) -->
      </svg>
      <div class="particles" id="particles" aria-hidden="true"></div>
      <div class="stars" id="stars" aria-hidden="true"></div>
    </div>

    <div class="error-content">
      <h1>404</h1>
      <p class="error-message">頁面在星際迷航中迷失了...</p>
      <nav class="error-actions" aria-label="錯誤頁面導航">
        <a href="/" class="btn btn-primary">🚀 返回發射台(首頁)</a>
        <a href="/sitemap" class="btn btn-secondary">🗺️ 查看星圖(網站地圖)</a>
        <button class="btn btn-ghost" id="reportBtn">📡 回報斷訊</button>
      </nav>
      <form class="search-form" role="search" aria-label="站內搜尋">
        <label for="site-search" class="visually-hidden">搜尋內容</label>
        <input type="search" id="site-search" name="q" placeholder="搜尋你想找的星球..." autocomplete="off">
        <button type="submit">🔍</button>
      </form>
    </div>
  </main>

  <script src="404.js" defer></script>
</body>
</html>

CSS 核心樣式(關鍵動畫與響應式)

/* 404.css 關鍵片段 */
.error-404 {
  min-height: 100vh;
  display: grid;
  place-items: center;
  background: radial-gradient(ellipse at center, #0d0d1a 0%, #000 100%);
  color: #e0e0e0;
  font-family: "Noto Sans TC", system-ui, sans-serif;
  overflow: hidden;
  position: relative;
}

.space-scene { position: relative; width: 100%; max-width: 400px; aspect-ratio: 2/3; }
.astronaut { width: 100%; height: 100%; filter: drop-shadow(0 0 30px #3498db88); animation: float 6s ease-in-out infinite; }
@keyframes float { 0%, 100% { transform: translateY(0) rotate(-2deg); } 50% { transform: translateY(-15px) rotate(2deg); } }

/* 視差效果 */
.stars { position: absolute; inset: 0; background-image: radial-gradient(1px 1px at 20px 30px, #fff, transparent), radial-gradient(1px 1px at 80px 150px, #fff, transparent), radial-gradient(1px 1px at 150px 80px, #fff, transparent); background-size: 200px 200px; animation: starMove 60s linear infinite; opacity: 0.6; }
@keyframes starMove { from { transform: translate(0,0); } to { transform: translate(-200px, -200px); } }

.particles { position: absolute; inset: 0; pointer-events: none; }
.particle { position: absolute; width: 6px; height: 6px; border-radius: 50%; background: #f39c12; opacity: 0; animation: burst 0.8s ease-out forwards; }
@keyframes burst { 0% { transform: scale(0); opacity: 1; } 100% { transform: translate(var(--tx), var(--ty)) scale(1); opacity: 0; } }

.error-content { text-align: center; padding: 2rem; z-index: 10; }
.error-404 h1 { font-size: clamp(6rem, 20vw, 12rem); font-weight: 800; line-height: 1; background: linear-gradient(135deg, #3498db, #9b59b6, #e74c3c); -webkit-background-clip: text; background-clip: text; color: transparent; animation: glitch 3s infinite; }
@keyframes glitch { 0%, 90%, 100% { text-shadow: none; } 92% { text-shadow: 2px 0 #e74c3c, -2px 0 #3498db; } 94% { text-shadow: -2px 0 #e74c3c, 2px 0 #3498db; } }

.error-message { font-size: 1.2rem; margin: 1rem 0 2rem; color: #aaa; }
.error-actions { display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap; margin-bottom: 2rem; }
.btn { padding: 0.8rem 1.5rem; border-radius: 50px; font-weight: 600; text-decoration: none; transition: transform 0.2s, box-shadow 0.2s; }
.btn:hover { transform: translateY(-2px); }
.btn-primary { background: #3498db; color: white; box-shadow: 0 4px 15px #3498db66; }
.btn-secondary { background: transparent; color: #3498db; border: 2px solid #3498db; }
.btn-ghost { background: transparent; color: #aaa; border: 2px solid #444; }
.search-form { display: flex; gap: 0.5rem; justify-content: center; max-width: 320px; margin: 0 auto; }
.search-form input { flex: 1; padding: 0.7rem 1rem; border: 2px solid #333; background: #111; color: #eee; border-radius: 50px; outline: none; }
.search-form input:focus { border-color: #3498db; box-shadow: 0 0 0 3px #3498db44; }
.search-form button { width: 48px; height: 48px; border-radius: 50%; background: #3498db; color: white; border: none; cursor: pointer; }

.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }

@media (prefers-reduced-motion: reduce) {
  .astronaut, .stars, .particle { animation: none !important; }
  .error-404 h1 { animation: none; }
}

JavaScript 互動邏輯(視差、粒子爆炸、回報、鍵盤控制)

// 404.js
const scene = document.getElementById('spaceScene');
const astronaut = document.querySelector('.astronaut');
const particles = document.getElementById('particles');
const reportBtn = document.getElementById('reportBtn');

// 1. 滑鼠視差
scene.addEventListener('mousemove', e => {
  const { innerWidth: w, innerHeight: h } = window;
  const x = (e.clientX - w/2) / w * 30;
  const y = (e.clientY - h/2) / h * 30;
  astronaut.style.transform = `translate(${x}px, ${y}px) rotate(${x/10}deg)`;
});
scene.addEventListener('mouseleave', () => astronaut.style.transform = '');

// 2. 點擊粒子爆炸
scene.addEventListener('click', e => {
  for (let i = 0; i < 12; i++) {
    const p = document.createElement('div');
    p.className = 'particle';
    const angle = (Math.PI * 2 / 12) * i;
    const dist = 80 + Math.random() * 40;
    p.style.setProperty('--tx', `${Math.cos(angle) * dist}px`);
    p.style.setProperty('--ty', `${Math.sin(angle) * dist}px`);
    p.style.left = `${e.clientX}px`;
    p.style.top = `${e.clientY}px`;
    particles.appendChild(p);
    p.addEventListener('animationend', () => p.remove());
  }
});

// 3. 鍵盤控制太空人漂浮
document.addEventListener('keydown', e => {
  const step = 10;
  const curr = astronaut.style.transform.match(/translate\(([^,]+)px,\s*([^)]+)px\)/);
  let x = curr ? parseFloat(curr[1]) : 0;
  let y = curr ? parseFloat(curr[2]) : 0;
  switch(e.key) {
    case 'ArrowLeft': x -= step; break;
    case 'ArrowRight': x += step; break;
    case 'ArrowUp': y -= step; break;
    case 'ArrowDown': y += step; break;
    default: return;
  }
  x = Math.max(-100, Math.min(100, x));
  y = Math.max(-100, Math.min(100, y));
  astronaut.style.transform = `translate(${x}px, ${y}px) rotate(${x/10}deg)`;
  astronaut.style.transition = 'transform 0.1s';
  setTimeout(() => astronaut.style.transition = '', 100);
});

// 4. 回報 404(發送到後端分析)
reportBtn.addEventListener('click', async () => {
  reportBtn.disabled = true;
  reportBtn.textContent = '📡 發射中...';
  try {
    await fetch('/api/404-report', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        url: window.location.href,
        referrer: document.referrer,
        ua: navigator.userAgent,
        timestamp: new Date().toISOString()
      })
    });
    reportBtn.textContent = '✅ 訊號已發送';
    reportBtn.classList.add('btn-primary');
    reportBtn.classList.remove('btn-ghost');
  } catch {
    reportBtn.textContent = '❌ 發射失敗';
  }
});

太空人 SVG 完整路徑(可直接內聯)

<svg class="astronaut" viewBox="0 0 200 300" fill="none" xmlns="https://www.w3.org/2000/svg">
  <!-- 頭盔 -->
  <ellipse cx="100" cy="60" rx="50" ry="55" fill="#ecf0f1" stroke="#2c3e50" stroke-width="3"/>
  <ellipse cx="100" cy="50" rx="35" ry="30" fill="#34495e" opacity="0.3"/> <!-- 面罩反光 -->
  <!-- 身體 -->
  <rect x="50" y="110" width="100" height="120" rx="20" fill="#2c3e50" stroke="#1a252f" stroke-width="3"/>
  <!-- 手臂 -->
  <rect x="10" y="130" width="40" height="100" rx="15" fill="#34495e" stroke="#2c3e50" stroke-width="2" transform="rotate(-15 30 180)"/>
  <rect x="150" y="130" width="40" height="100" rx="15" fill="#34495e" stroke="#2c3e50" stroke-width="2" transform="rotate(15 170 180)"/>
  <!-- 腿 -->
  <rect x="60" y="230" width="35" height="70" rx="10" fill="#2c3e50" stroke="#1a252f" stroke-width="2"/>
  <rect x="105" y="230" width="35" height="70" rx="10" fill="#2c3e50" stroke="#1a252f" stroke-width="2"/>
  <!-- 氧氣管(斷裂動畫可用 stroke-dasharray 實現) -->
  <path d="M100 55 Q130 20 160 10" stroke="#e74c3c" stroke-width="3" fill="none" stroke-dasharray="10 5" stroke-linecap="round"/>
  <!-- 背包推進器 -->
  <rect x="40" y="120" width="15" height="80" rx="5" fill="#7f8c8d" stroke="#2c3e50" stroke-width="2"/>
  <rect x="145" y="120" width="15" height="80" rx="5" fill="#7f8c8d" stroke="#2c3e50" stroke-width="2"/>
  <circle cx="47.5" cy="210" r="8" fill="#e74c3c" opacity="0.8"><animate attributeName="opacity" values="0.8;0.2;0.8" dur="0.5s" repeatCount="indefinite"/></circle>
  <circle cx="152.5" cy="210" r="8" fill="#e74c3c" opacity="0.8"><animate attributeName="opacity" values="0.2;0.8;0.2" dur="0.5s" repeatCount="indefinite"/></circle>
</svg>

部署與監控清單

  • ✅ 伺服器正確回傳 404 Not Found 狀態碼(非 200/302)
  • ✅ <meta name="robots" content="noindex"> 防止搜尋引擎收錄
  • ✅ 記錄 404 日誌:URL、Referrer、UA、時間,定期分析修復死連結
  • ✅ 檢查 prefers-reduced-motion 媒體查詢,尊重用戶動畫偏好
  • ✅ 測試無障礙:NVDA/VoiceOver 朗讀流程、鍵盤完整操作、色彩對比度
  • ✅ 壓縮 SVG、啟用 Brotli/Gzip、CDN 快取、Cache-Control: public, max-age=31536000, immutable

總結

一個優秀的 404 頁面 = 品牌故事 + 實用導航 + 愉悅互動 + 數據回收。用 HTML5 語義結構、CSS3 關鍵幂動畫/視差/粒子系統、Vanilla JS 輕量互動,零依賴打造專屬品牌記憶點。下次用戶迷路時,給他們一場星際探險,而非冰冷的「Not Found」。

copyright © 萬盛學電腦網 all rights reserved