萬盛學電腦網

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

原生 JavaScript 實現圖片放大鏡效果(電商級組件封裝)

電商商品詳情頁常見的放大鏡效果,滑過小圖顯示大圖局部放大。本文從核心算法到完整組件封裝,逐步實現一個無依賴、高性能的放大鏡組件。

核心原理

  1. 小圖容器: 顯示縮略圖,作為參考基準。
  2. 遮罩層: 覆蓋小圖,捕獲鼠標事件,尺寸與小圖一致。
  3. 鏡片: 遮罩層上的半透明矩形,跟隨鼠標移動,指示放大區域。
  4. 大圖容器: 固定尺寸、overflow:hidden,內部放置大圖。
  5. 坐標映射: 鏡片在小圖中的相對位置,映射到大圖在容器中的偏移量。

關鍵映射公式

// 鏡片中心相對遮罩層的比例
var ratioX = mirrorLeft / (maskWidth - mirrorWidth);
var ratioY = mirrorTop  / (maskHeight - mirrorHeight);

// 大圖偏移 = -比例 * (大圖尺寸 - 容器尺寸)
bigImg.style.left = -ratioX * (bigImgWidth - bigDivWidth) + 'px';
bigImg.style.top  = -ratioY * (bigImgHeight - bigDivHeight) + 'px';

完整組件封裝 (ES6 類風格)

class Magnifier {
  constructor(containerId, smallImgSrc, largeImgSrc, options = {}) {
    this.container = document.getElementById(containerId);
    this.smallSrc = smallImgSrc;
    this.largeSrc = largeImgSrc;
    this.mirrorSize = options.mirrorSize || { width: 100, height: 100 };
    this.viewSize = options.viewSize || { width: 400, height: 400 };
    this.init();
  }
  
  init() {
    this.createStructure();
    this.bindEvents();
    this.loadImages();
  }
  
  createStructure() {
    // 創建 DOM 結構:smallDiv > mask + mirror + smallImg, bigDiv > bigImg
    // 設置樣式:position, overflow, z-index 等
  }
  
  loadImages() {
    this.smallImg.onload = () => {
      // 根據小圖尺寸初始化容器、遮罩、鏡片大小
      // 設置大圖容器位置
    };
  }
  
  bindEvents() {
    this.mask.onmouseenter = () => { this.show(); };
    this.mask.onmouseleave = () => { this.hide(); };
    this.mask.onmousemove = (e) => { this.move(e); };
  }
  
  move(e) {
    // 計算鏡片位置(邊界限制)
    // 計算比例並移動大圖
  }
  
  show() { this.bigDiv.style.display = 'block'; this.mirror.style.display = 'block'; }
  hide() { this.bigDiv.style.display = 'none'; this.mirror.style.display = 'none'; }
}

// 使用
new Magnifier('magnifier-container', 'small.jpg', 'large.jpg', {
  mirrorSize: { width: 120, height: 120 },
  viewSize: { width: 500, height: 500 }
});

進階功能擴展

  • 多圖切換:縮略圖列表點擊切換小圖/大圖 src。
  • 鏡片形狀:圓形、方形可配置(border-radius)。
  • 觸屏支持:touch 事件適配移動端。
  • 懸浮/內嵌模式:大圖容器位置可配置(右側、底部、覆蓋層)。

現代替代方案

生產環境建議使用成熟庫如 zoom.js、medium-zoom 或 CSS transform: scale() 方案,兼容性更好、維護成本更低。

copyright © 萬盛學電腦網 all rights reserved