萬盛學電腦網

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

jQuery 實現圖片縮放拖動查看器:從原生滾輪到完整交互組件

圖片查看器需支持滾輪縮放、拖動平移、雙擊重置、觸屏手勢。原文提供了基礎 jQuery 實現,但存在版本依賴、事件綁定洩漏、邊界控制缺失等問題。本文重構為現代、健壯、可復用的組件模式,並對比原生/CSS 替代方案。

一、核心交互邏輯

  • 縮放:滾輪向上放大、向下縮小,以滑鼠位置為中心
  • 平移:按住滑鼠左鍵拖動圖片
  • 邊界限制:圖片不超出容器可視區(或允許邊界彈性)
  • 重置:雙擊/按鈕恢復初始縮放與位置

二、現代重構實現 (Vanilla JS + CSS Transform)

HTML 結構

<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>

核心 CSS (關鍵:transform-origin + transform)

.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; }

核心 JS 類 (ES6 Class,無依賴)


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 });

三、原文 jQuery 代碼問題分析

  • $.browser.mozilla:jQuery 1.9+ 已移除,需用特性檢測
  • bind/unbind:已棄用,改用 on/off
  • 縮放中心固定為圖片中心,非滑鼠位置,體驗差
  • 拖動計算未考慮容器偏移 (offset() 含邊框/滾動),導致抖動
  • 無邊界限制,圖片可拖出可視區
  • 無觸屏支持,移動端不可用
  • 定時器動畫 (setInterval) 幂率不穩,現代用 requestAnimationFrame 或 CSS transition

四、CSS 替代方案:純 CSS 縮放 (無拖動)


.zoom-on-hover img {
    transition: transform 0.3s ease;
    transform-origin: center center;
}
.zoom-on-hover:hover img {
    transform: scale(1.5);
}

適用於簡單懸停放大,無需 JS。

五、生態庫推薦 (生產環境首選)

  • PhotoSwipe:專業畫廊、手勢、全屏、無依賴
  • Medium Zoom:輕量、點擊全屏、漸變動畫
  • Zoom.js:Medium 風格、ESM、TypeScript
  • Viewer.js:功能全、鍵盤導航、旋轉、鏡像

六、總結

  1. 核心數學:transform: translate(x,y) scale(s) + transform-origin: 0 0
  2. 縮放中心補償:pos = center - (center - pos) * (newScale/oldScale)
  3. 邊界限制:根據縮放後尺寸與容器尺寸計算合法位移範圍
  4. 事件處理:wheel (縮放) + mousedown/mousemove/mouseup (拖動) + 觸屏映射
  5. 現代化:Class 封裝、requestAnimationFrame/CSS Transition、passive: false 阻止默認滾動

將 ImageViewer 類納入組件庫,下次需求「圖片可縮放拖動」直接 new ImageViewer('.container'),專業交互即刻交付。

copyright © 萬盛學電腦網 all rights reserved