燈箱是圖片畫廊、產品展示的標配交互。本文實現一個支持鍵盤導航、響應式縮放、圖片預加載、ESC 關閉、滾動鎖定的完整燈箱組件。
class Lightbox {
constructor(options = {}) {
this.selector = options.selector || '[data-lightbox]';
this.images = [...document.querySelectorAll(this.selector)];
this.currentIndex = 0;
this.isOpen = false;
this.init();
}
init() {
// 綁定觸發元素點擊
this.images.forEach((el, i) => {
el.addEventListener('click', e => this.open(i, e));
});
// 鍵盤事件
document.addEventListener('keydown', e => this.onKeydown(e));
// 窗口變化防抖
let resizeTimer;
window.addEventListener('resize', () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => this.onResize(), 100);
});
}
open(index, event) {
event.preventDefault();
this.currentIndex = index;
this.buildDOM();
this.loadImage(this.images[index].dataset.src || this.images[index].href);
this.lockScroll();
this.isOpen = true;
}
buildDOM() {
// 構建燈箱 DOM 結構
this.overlay = document.createElement('div');
this.overlay.className = 'lightbox-overlay';
this.overlay.innerHTML = `
`;
document.body.appendChild(this.overlay);
// 綁定內部事件
this.overlay.querySelector('.lightbox-close').onclick = () => this.close();
this.overlay.querySelector('.lightbox-prev').onclick = () => this.navigate(-1);
this.overlay.querySelector('.lightbox-next').onclick = () => this.navigate(1);
this.overlay.onclick = e => { if (e.target === this.overlay) this.close(); };
// 強制重繪觸發動畫
requestAnimationFrame(() => this.overlay.classList.add('show'));
}
loadImage(src) {
this.imageEl = this.overlay.querySelector('.lightbox-image');
this.captionEl = this.overlay.querySelector('.lightbox-caption');
// 顯示載入中
this.imageEl.src = '';
this.captionEl.textContent = `${this.currentIndex + 1} / ${this.images.length}`;
const img = new Image();
img.onload = () => {
this.naturalWidth = img.width;
this.naturalHeight = img.height;
this.imageEl.src = src;
this.adjustSize();
};
img.onerror = () => {
this.captionEl.textContent = '圖片加載失敗';
};
img.src = src;
}
adjustSize() {
// 響應式縮放:適應視口 90%,保持比例
const maxW = window.innerWidth * 0.9;
const maxH = window.innerHeight * 0.85;
const ratio = Math.min(maxW / this.naturalWidth, maxH / this.naturalHeight, 1);
this.imageEl.style.width = this.naturalWidth * ratio + 'px';
this.imageEl.style.height = this.naturalHeight * ratio + 'px';
}
navigate(dir) {
const newIndex = (this.currentIndex + dir + this.images.length) % this.images.length;
this.currentIndex = newIndex;
this.loadImage(this.images[newIndex].dataset.src || this.images[newIndex].href);
}
onKeydown(e) {
if (!this.isOpen) return;
if (e.key === 'Escape') this.close();
if (e.key === 'ArrowLeft') this.navigate(-1);
if (e.key === 'ArrowRight') this.navigate(1);
}
onResize() {
if (this.isOpen && this.naturalWidth) this.adjustSize();
}
lockScroll() {
document.body.style.overflow = 'hidden';
document.body.style.paddingRight = window.innerWidth - document.documentElement.clientWidth + 'px';
}
unlockScroll() {
document.body.style.overflow = '';
document.body.style.paddingRight = '';
}
close() {
this.overlay.classList.remove('show');
setTimeout(() => {
this.overlay.remove();
this.unlockScroll();
this.isOpen = false;
}, 300); // 匹配 CSS 動畫時長
}
}
.lightbox-overlay {
position: fixed; inset: 0; background: rgba(0,0,0,.9);
display: flex; align-items: center; justify-content: center;
z-index: 9999; opacity: 0; visibility: hidden;
transition: opacity .3s, visibility .3s;
}
.lightbox-overlay.show { opacity: 1; visibility: visible; }
.lightbox-content { position: relative; max-width: 90vw; max-height: 85vh; }
.lightbox-image { display: block; max-width: 100%; max-height: 85vh; }
.lightbox-caption { color: #fff; text-align: center; padding: 10px; font-size: 14px; }
.lightbox-close, .lightbox-prev, .lightbox-next {
position: absolute; background: none; border: none; color: #fff; font-size: 30px;
cursor: pointer; padding: 10px; opacity: .7; transition: opacity .2s;
}
.lightbox-close { top: 20px; right: 20px; }
.lightbox-prev { left: 20px; top: 50%; transform: translateY(-50%); }
.lightbox-next { right: 20px; top: 50%; transform: translateY(-50%); }
.lightbox-close:hover, .lightbox-prev:hover, .lightbox-next:hover { opacity: 1; }
<div class="gallery">
<a href="large1.jpg" data-lightbox data-title="風景1">
<img src="thumb1.jpg" alt="風景1">
</a>
<a href="large2.jpg" data-lightbox data-title="風景2">
<img src="thumb2.jpg" alt="風景2">
</a>
</div>
<script>
new Lightbox({ selector: '[data-lightbox]' });
</script>
這個組件展示了現代原生 JS 開發組件的完整最佳實踐模式。