電商商品圖、相簿縮圖常需「滑鼠懸停顯示大圖」。本文實作完整預覽組件:事件委派、動態建立預覽層、游標跟隨定位、邊界檢測防溢出、圖片預載入、錯誤處理、無障礙鍵盤支援。
class ImagePreview {
constructor(containerSelector, options = {}) {
this.$container = $(containerSelector);
this.offsetX = options.offsetX || 15;
this.offsetY = options.offsetY || 15;
this.$preview = null;
this.bindEvents();
}
bindEvents() {
this.$container.on('mouseenter', 'img[data-preview]', (e) => this.show(e));
this.$container.on('mousemove', 'img[data-preview]', (e) => this.move(e));
this.$container.on('mouseleave', 'img[data-preview]', () => this.hide());
// 鍵盤支援
this.$container.on('focusin', 'img[data-preview]', (e) => this.show(e));
this.$container.on('focusout', 'img[data-preview]', () => this.hide());
}
show(e) {
const $img = $(e.currentTarget);
const src = $img.data('preview') || $img.attr('src');
if (!src) return;
// 預載入確保尺寸正確
this.preload(src).then(img => {
this.$preview = $('
', {
src: img.src,
id: 'img-preview',
css: {
position: 'fixed', // 相對視窗定位,不受滾動影響
zIndex: 9999,
maxWidth: '90vw', maxHeight: '90vh',
boxShadow: '0 4px 20px rgba(0,0,0,.3)',
borderRadius: '4px',
pointerEvents: 'none' // 避免干擾滑鼠事件
}
}).appendTo('body');
this.move(e); // 初始定位
}).catch(() => this.showError($img));
}
preload(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = src;
});
}
move(e) {
if (!this.$preview) return;
let x = e.clientX + this.offsetX;
let y = e.clientY + this.offsetY;
const pw = this.$preview.outerWidth(), ph = this.$preview.outerHeight();
const vw = $(window).width(), vh = $(window).height();
// 邊界檢測:防止超出視窗
if (x + pw > vw) x = e.clientX - pw - this.offsetX;
if (y + ph > vh) y = e.clientY - ph - this.offsetY;
this.$preview.css({ left: x, top: y });
}
hide() {
this.$preview?.remove();
this.$preview = null;
}
showError($img) {
$img.after('圖片載入失敗');
setTimeout(() => $img.next('.preview-error').remove(), 2000);
}
}
// 初始化
new ImagePreview('.gallery', { offsetX: 20, offsetY: 20 });
<div class="gallery">
<img src="thumb-1.jpg" data-preview="large-1.jpg" alt="商品 1" tabindex="0">
<img src="thumb-2.jpg" data-preview="large-2.jpg" alt="商品 2" tabindex="0">
</div>
/* 縮圖樣式 */
.gallery img { width: 150px; height: 120px; object-fit: cover; cursor: zoom-in; margin: 10px; }
/* 預覽層動畫 */
#img-preview { animation: fadeIn 0.15s ease-out; }
@keyframes fadeIn { from { opacity: 0; transform: scale(0.95); } to { opacity: 1; transform: scale(1); } }
.gallery img { position: relative; }
.gallery img[data-preview]::after {
content: ''; position: absolute; left: 100%; top: 0; margin-left: 10px;
width: 300px; height: 200px; background: var(--preview-url) center/cover no-repeat;
border: 1px solid #ccc; box-shadow: 0 4px 12px rgba(0,0,0,.2); opacity: 0; pointer-events: none;
transition: opacity 0.2s; z-index: 100;
}
.gallery img[data-preview]:hover::after { opacity: 1; }
JS 版本靈活度高(動態定位、預載、錯誤處理、無障礙),CSS 版本零依賴、效能極佳,按專案複雜度選型。