萬盛學電腦網

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

Web 前端彈性下拉刷新特效實作:原理、動畫曲線與跨平台適配

模式起源與價值

「下拉刷新」由 Loren Brichter 為 Tweetie (iOS) 發明,後成為行動端標準交互。核心價值:將「想看新內容」的自然下拉手勢直接映射為刷新動作,消除獨立按鈕,實現意圖與行為合一。

適用場景

  • 垂直列表/資訊流 (社群動態、新聞、郵件、聊天記錄)。
  • 需頻繁獲取最新資料的頁面。
  • 行動 Web App、PWA、Hybrid App WebView 內容區。

交互階段與動畫曲線

  1. 下拉階段:使用者向下拖拽列表,阻力隨位移增加 (非線性),視覺回饋指示器跟隨拉伸/旋轉。
    • 阻力函數:offset = dragDistance * resistanceFactor (如 Math.min(drag * 0.5, MAX_OFFSET))。
    • 指示器:箭頭旋轉 0°→180°、環狀進度條漸漲、自定義插畫變形。
  2. 臨界點觸發:釋放時位移超過閾值 (通常 60-80px) → 進入刷新狀態;否則彈回取消。
  3. 刷新階段:列表固定在閾值位置,顯示載入動畫 (Spinner、骨架屏、品牌動畫)。
  4. 完成/失敗:資料到位 → 平滑縮回頂部並插入新資料;失敗 → 震動回饋 + 錯誤提示,允許再次下拉。

核心實作架構 (Vanilla JS)

class PullToRefresh {
  constructor(scrollContainer, options = {}) {
    this.container = scrollContainer;
    this.threshold = options.threshold || 70;
    this.resistance = options.resistance || 0.5;
    this.onRefresh = options.onRefresh || (() => Promise.resolve());
    this.indicator = this.createIndicator();
    this.state = 'idle'; // idle | dragging | armed | refreshing | settling
    this.startY = 0;
    this.currentY = 0;
    this.bindEvents();
  }

  createIndicator() {
    const el = document.createElement('div');
    el.className = 'ptr-indicator';
    el.innerHTML = `
`; this.container.parentElement.insertBefore(el, this.container); return el; } bindEvents() { // 支援觸控與滑鼠 (桌面測試用) const events = { start: ['touchstart', 'mousedown'], move: ['touchmove', 'mousemove'], end: ['touchend', 'touchcancel', 'mouseup', 'mouseleave'] }; events.start.forEach(e => this.container.addEventListener(e, this.onStart.bind(this), {passive: true})); events.move.forEach(e => window.addEventListener(e, this.onMove.bind(this), {passive: false})); events.end.forEach(e => window.addEventListener(e, this.onEnd.bind(this))); } getClientY(e) { return e.touches ? e.touches[0].clientY : e.clientY; } onStart(e) { if (this.state !== 'idle') return; if (this.container.scrollTop > 0) return; // 僅在頂部觸發 this.startY = this.getClientY(e); this.state = 'dragging'; this.indicator.style.transition = 'none'; } onMove(e) { if (this.state !== 'dragging') return; const dragY = this.getClientY(e) - this.startY; if (dragY <= 0) return; // 向上拖拽忽略 e.preventDefault(); // 阻止頁面滾動 this.currentY = Math.min(dragY * this.resistance, this.threshold * 1.5); this.container.style.transform = `translateY(${this.currentY}px)`; this.indicator.style.transform = `translateY(${this.currentY}px)`; // 更新指示器狀態 const progress = Math.min(this.currentY / this.threshold, 1); this.indicator.style.setProperty('--progress', progress); if (this.currentY >= this.threshold) { this.indicator.classList.add('armed'); this.state = 'armed'; } else { this.indicator.classList.remove('armed'); } } async onEnd() { if (this.state !== 'dragging' && this.state !== 'armed') return; if (this.state === 'armed') { this.state = 'refreshing'; this.indicator.classList.add('refreshing'); this.indicator.classList.remove('armed'); // 固定在閾值位置 this.container.style.transition = 'transform 0.3s ease'; this.container.style.transform = `translateY(${this.threshold}px)`; this.indicator.style.transition = 'transform 0.3s ease'; this.indicator.style.transform = `translateY(${this.threshold}px)`; try { await this.onRefresh(); this.complete(true); } catch (err) { this.complete(false); } } else { this.cancel(); } } complete(success) { this.indicator.classList.remove('refreshing'); this.indicator.classList.add(success ? 'success' : 'error'); // 短暫停留後縮回 setTimeout(() => { this.container.style.transition = 'transform 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94)'; this.container.style.transform = 'translateY(0)'; this.indicator.style.transition = 'transform 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94), opacity 0.3s'; this.indicator.style.transform = 'translateY(0)'; this.indicator.style.opacity = '0'; setTimeout(() => { this.indicator.style.opacity = '1'; this.indicator.className = 'ptr-indicator'; this.state = 'idle'; }, 400); }, success ? 400 : 1000); } cancel() { this.container.style.transition = 'transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)'; this.container.style.transform = 'translateY(0)'; this.indicator.style.transition = 'transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)'; this.indicator.style.transform = 'translateY(0)'; this.state = 'idle'; } } // 使用範例 new PullToRefresh(document.querySelector('.feed-list'), { threshold: 70, onRefresh: async () => { const res = await fetch('/api/feed/latest'); const data = await res.json(); prependFeedItems(data.items); // 自行實作插入邏輯 } });

關鍵 CSS 變數與動畫

.ptr-indicator {
  position: absolute;
  top: -80px; left: 50%; transform: translateX(-50%);
  width: 40px; height: 40px;
  display: flex; align-items: center; justify-content: center;
  --progress: 0;
}
.ptr-arrow {
  transition: transform 0.2s ease;
  transform: rotate(calc(var(--progress) * 180deg));
}
.ptr-spinner {
  opacity: 0; transition: opacity 0.2s;
  width: 24px; height: 24px; border: 2px solid #ccc;
  border-top-color: #1f605b; border-radius: 50%;
  animation: spin 0.8s linear infinite paused;
}
.ptr-indicator.refreshing .ptr-arrow { opacity: 0; }
.ptr-indicator.refreshing .ptr-spinner { opacity: 1; animation-play-state: running; }
.ptr-indicator.success .ptr-spinner { border-top-color: #28a745; }
.ptr-indicator.error .ptr-spinner { border-top-color: #dc3545; }
@keyframes spin { to { transform: rotate(360deg); } }

跨平台適配關鍵

平台挑戰對策
iOS Safari橡皮筋效果原生干擾overscroll-behavior-y: contain 於容器;或使用 position: sticky 方案
Android ChromePull-to-refresh 瀏覽器原生手勢同上;或在 html, body 設定 overscroll-behavior: none (謹慎,影響整頁)
桌面瀏覽器滑鼠拖拽非自然操作視為輔助功能,保留但非主要交互;提供按鈕刷新備選
WebView (Hybrid)原生下拉刷新衝突原生層攔截或關閉 WebView 原生 PTR,由 JS 統一處理

無障礙與體驗細節

  • 提供「刷新」按鈕作為鍵盤/螢幕閱讀器替代操作。
  • 載入中以 aria-live="polite" 宣告狀態。
  • 尊重 prefers-reduced-motion 簡化動畫。
  • 錯誤狀態提供「重試」明確動作。

彈性下拉刷新是行動端資訊流的靈魂交互。深入理解其物理隱喻、狀態機設計、動畫曲線與平台差異,能打造媲美原生 App 的流暢體驗。

copyright © 萬盛學電腦網 all rights reserved