電商商品詳情頁常見的放大鏡效果,滑過小圖顯示大圖局部放大。本文從核心算法到完整組件封裝,逐步實現一個無依賴、高性能的放大鏡組件。
// 鏡片中心相對遮罩層的比例
var ratioX = mirrorLeft / (maskWidth - mirrorWidth);
var ratioY = mirrorTop / (maskHeight - mirrorHeight);
// 大圖偏移 = -比例 * (大圖尺寸 - 容器尺寸)
bigImg.style.left = -ratioX * (bigImgWidth - bigDivWidth) + 'px';
bigImg.style.top = -ratioY * (bigImgHeight - bigDivHeight) + 'px';
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 }
});
生產環境建議使用成熟庫如 zoom.js、medium-zoom 或 CSS transform: scale() 方案,兼容性更好、維護成本更低。