「下拉刷新」由 Loren Brichter 為 Tweetie (iOS) 發明,後成為行動端標準交互。核心價值:將「想看新內容」的自然下拉手勢直接映射為刷新動作,消除獨立按鈕,實現意圖與行為合一。
offset = dragDistance * resistanceFactor (如 Math.min(drag * 0.5, MAX_OFFSET))。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); // 自行實作插入邏輯
}
});
.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 Chrome | Pull-to-refresh 瀏覽器原生手勢 | 同上;或在 html, body 設定 overscroll-behavior: none (謹慎,影響整頁) |
| 桌面瀏覽器 | 滑鼠拖拽非自然操作 | 視為輔助功能,保留但非主要交互;提供按鈕刷新備選 |
| WebView (Hybrid) | 原生下拉刷新衝突 | 原生層攔截或關閉 WebView 原生 PTR,由 JS 統一處理 |
aria-live="polite" 宣告狀態。prefers-reduced-motion 簡化動畫。彈性下拉刷新是行動端資訊流的靈魂交互。深入理解其物理隱喻、狀態機設計、動畫曲線與平台差異,能打造媲美原生 App 的流暢體驗。