圖片查看器需支持滾輪縮放、拖動平移、雙擊重置、觸屏手勢。原文提供了基礎 jQuery 實現,但存在版本依賴、事件綁定洩漏、邊界控制缺失等問題。本文重構為現代、健壯、可復用的組件模式,並對比原生/CSS 替代方案。
<div class="image-viewer">
<div class="viewer-container">
<img class="viewer-image" src="large.jpg" alt="可縮放圖片">
</div>
<div class="viewer-controls">
<button class="btn-zoom-in">+</button>
<button class="btn-zoom-out">-</button>
<button class="btn-reset">⟲</button>
</div>
</div>
.image-viewer {
position: relative;
width: 100%; height: 500px;
overflow: hidden;
background: #f0f0f0;
user-select: none;
}
.viewer-container {
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
display: flex;
align-items: center;
justify-content: center;
/* 變換原點始終為容器中心,配合 translate 實現以中心縮放 */
}
.viewer-image {
max-width: none; max-height: none; /* 允許超出容器 */
transform-origin: 0 0; /* 關鍵:以左上角為原點,配合 translate(x,y) scale(s) */
transition: transform 0.15s ease-out; /* 平滑縮放 */
will-change: transform;
cursor: grab;
}
.viewer-image:active { cursor: grabbing; }
class ImageViewer {
constructor(containerSelector, options = {}) {
this.container = document.querySelector(containerSelector);
this.img = this.container.querySelector('.viewer-image');
this.wrapper = this.container.querySelector('.viewer-container');
this.scale = 1;
this.minScale = options.minScale || 0.1;
this.maxScale = options.maxScale || 5;
this.scaleStep = options.scaleStep || 0.2;
this.pos = { x: 0, y: 0 }; // 圖片左上角相對容器中心的偏移
this.dragStart = null;
this.bindEvents();
this.reset();
}
bindEvents() {
// 滾輪縮放
this.container.addEventListener('wheel', e => this.onWheel(e), { passive: false });
// 拖動
this.img.addEventListener('mousedown', e => this.onDragStart(e));
window.addEventListener('mousemove', e => this.onDragMove(e));
window.addEventListener('mouseup', () => this.onDragEnd());
// 觸屏支持
this.img.addEventListener('touchstart', e => this.onTouchStart(e), { passive: false });
window.addEventListener('touchmove', e => this.onTouchMove(e), { passive: false });
window.addEventListener('touchend', () => this.onDragEnd());
// 雙擊重置
this.img.addEventListener('dblclick', () => this.reset());
// 控制按鈕
this.container.querySelector('.btn-zoom-in')?.addEventListener('click', () => this.zoom(1));
this.container.querySelector('.btn-zoom-out')?.addEventListener('click', () => this.zoom(-1));
this.container.querySelector('.btn-reset')?.addEventListener('click', () => this.reset());
// 圖片加載完成後居中
this.img.addEventListener('load', () => this.reset());
if (this.img.complete) this.reset();
}
// 統一變換應用
applyTransform() {
this.img.style.transform = `translate(${this.pos.x}px, ${this.pos.y}px) scale(${this.scale})`;
}
// 縮放 (以滑鼠位置為中心)
zoom(direction, clientX, clientY) {
const oldScale = this.scale;
this.scale = Math.max(this.minScale, Math.min(this.maxScale, this.scale + direction * this.scaleStep));
if (this.scale === oldScale) return;
if (clientX !== undefined) {
// 以滑鼠位置為中心縮放:調整位置補償
const rect = this.container.getBoundingClientRect();
const cx = clientX - rect.left - rect.width / 2;
const cy = clientY - rect.top - rect.height / 2;
const factor = this.scale / oldScale;
this.pos.x = cx - (cx - this.pos.x) * factor;
this.pos.y = cy - (cy - this.pos.y) * factor;
}
this.applyTransform();
this.clampPosition();
}
onWheel(e) {
e.preventDefault();
const direction = e.deltaY < 0 ? 1 : -1;
this.zoom(direction, e.clientX, e.clientY);
}
// 拖動邏輯
onDragStart(e) {
if (e.button !== 0) return; // 僅左鍵
e.preventDefault();
this.dragStart = {
x: e.clientX - this.pos.x,
y: e.clientY - this.pos.y
};
this.img.style.cursor = 'grabbing';
this.img.style.transition = 'none'; // 拖動時禁用過渡
}
onDragMove(e) {
if (!this.dragStart) return;
e.preventDefault();
this.pos.x = e.clientX - this.dragStart.x;
this.pos.y = e.clientY - this.dragStart.y;
this.applyTransform();
this.clampPosition();
}
onDragEnd() {
this.dragStart = null;
this.img.style.cursor = 'grab';
this.img.style.transition = 'transform 0.15s ease-out';
}
// 觸屏適配
onTouchStart(e) {
if (e.touches.length === 1) {
const t = e.touches[0];
this.onDragStart({ clientX: t.clientX, clientY: t.clientY, button: 0, preventDefault: ()=>e.preventDefault() });
} else if (e.touches.length === 2) {
// 雙指捏合縮放 (簡易版)
this.initialTouchDistance = this.getTouchDistance(e.touches[0], e.touches[1]);
this.initialScale = this.scale;
}
}
onTouchMove(e) {
if (e.touches.length === 1 && this.dragStart) {
const t = e.touches[0];
this.onDragMove({ clientX: t.clientX, clientY: t.clientY, preventDefault: ()=>e.preventDefault() });
} else if (e.touches.length === 2 && this.initialTouchDistance) {
const dist = this.getTouchDistance(e.touches[0], e.touches[1]);
const scale = this.initialScale * (dist / this.initialTouchDistance);
this.scale = Math.max(this.minScale, Math.min(this.maxScale, scale));
this.applyTransform();
this.clampPosition();
}
}
getTouchDistance(t1, t2) {
return Math.hypot(t1.clientX - t2.clientX, t1.clientY - t2.clientY);
}
// 邊界限制:圖片必須覆蓋容器 (無留白) 或允許留白
clampPosition() {
const cw = this.container.clientWidth;
const ch = this.container.clientHeight;
const iw = this.img.naturalWidth * this.scale;
const ih = this.img.naturalHeight * this.scale;
// 允許邊界:圖片小於容器時居中,大於時不超出
const maxX = Math.max(0, (iw - cw) / 2);
const maxY = Math.max(0, (ih - ch) / 2);
this.pos.x = Math.max(-maxX, Math.min(maxX, this.pos.x));
this.pos.y = Math.max(-maxY, Math.min(maxY, this.pos.y));
this.applyTransform();
}
reset() {
this.scale = 1;
this.pos = { x: 0, y: 0 };
this.img.style.transition = 'transform 0.3s ease-out';
this.applyTransform();
}
}
// 初始化
new ImageViewer('.image-viewer', { minScale: 0.2, maxScale: 4 });
$.browser.mozilla:jQuery 1.9+ 已移除,需用特性檢測bind/unbind:已棄用,改用 on/offoffset() 含邊框/滾動),導致抖動setInterval) 幂率不穩,現代用 requestAnimationFrame 或 CSS transition
.zoom-on-hover img {
transition: transform 0.3s ease;
transform-origin: center center;
}
.zoom-on-hover:hover img {
transform: scale(1.5);
}
適用於簡單懸停放大,無需 JS。
transform: translate(x,y) scale(s) + transform-origin: 0 0pos = center - (center - pos) * (newScale/oldScale)wheel (縮放) + mousedown/mousemove/mouseup (拖動) + 觸屏映射requestAnimationFrame/CSS Transition、passive: false 阻止默認滾動將 ImageViewer 類納入組件庫,下次需求「圖片可縮放拖動」直接 new ImageViewer('.container'),專業交互即刻交付。