萬盛學電腦網

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

原生 JavaScript 實現圖片燈箱彈窗組件完整教學

原生 JS 圖片燈箱:從核心邏輯到生產級組件

燈箱是圖片畫廊、產品展示的標配交互。本文實現一個支持鍵盤導航、響應式縮放、圖片預加載、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 動畫時長
  }
}

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

HTML 使用示例

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

進階優化清單

  • 觸摸滑動:添加 touchstart/move/end 實現手勢左右滑動
  • 縮放手勢:雙指縮放圖片 (Transform + scale)
  • 預加載鄰近:預加載前後 1-2 張圖片
  • 懶加載觸發:IntersectionObserver 監聽縮圖進入視口再初始化
  • 無障礙:ARIA 標籤、焦點管理、焦點陷阱
  • SSR 友好:構建時不操作 DOM,僅導出類

這個組件展示了現代原生 JS 開發組件的完整最佳實踐模式。

copyright © 萬盛學電腦網 all rights reserved