萬盛學電腦網

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

JavaScript 簡易焦點圖輪播:滑動門原理與模組化重構

效果預覽

經典的「滑動門」式焦點圖:

  • 5 張圖片水平排列,容器 overflow: hidden 僅顯示一張
  • 底部數字按鈕(1-5)切換對應圖片
  • 滑鼠懸停按鈕切換,無自動播放
  • CSS 控制可見性:.show { visibility: visible }

原始碼架構分析

<div class="area mid">
  <div id="imgbox">
    <ul id="pic_list">
      <li class="show"><img src="1.jpg" /></li>
      <li><img src="2.jpg" /></li>
      <li><img src="3.jpg" /></li>
      <li><img src="4.jpg" /></li>
      <li><img src="5.jpg" /></li>
    </ul>
  </div>
  <div class="button">
    <ul id="button">
      <li class="current">1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
    </ul>
  </div>
</div>

CSS 佈局關鍵

.area { width: 240px; height: 270px; margin: 150px auto; overflow: hidden; position: relative; background: #999; }
#pic_list { position: relative; width: 240px; height: 270px; }
#pic_list li { position: absolute; top: 0; left: 0; visibility: hidden; }
#pic_list li.show { visibility: visible; }
#pic_list li img { vertical-align: middle; width: 240px; height: 270px; object-fit: cover; }
.button { width: 100%; height: 30px; line-height: 30px; background: #ccc; position: absolute; bottom: 0; }
#button { float: right; padding-right: 10px; }
#button li { float: left; width: 24px; height: 24px; margin: 3px; text-align: center; 
  background: #000; color: #fff; font: 12px Arial; cursor: pointer; border-radius: 50%; }
#button li.current { background: #f00; }

原始 JavaScript 邏輯重構(ES6 模組化)

class SimpleSlider {
  constructor(containerSelector) {
    this.container = document.querySelector(containerSelector);
    if (!this.container) return;
    
    this.picList = this.container.querySelector("#pic_list");
    this.slides = Array.from(this.picList.children);
    this.btnList = this.container.querySelector("#button");
    this.buttons = Array.from(this.btnList.children);
    this.currentIndex = 0;
    this.timer = null;
    
    this.init();
  }
  
  init() {
    this.bindEvents();
    // 可選:自動播放
    // this.startAuto();
    // this.container.addEventListener("mouseenter", () => this.stopAuto());
    // this.container.addEventListener("mouseleave", () => this.startAuto());
  }
  
  bindEvents() {
    this.buttons.forEach((btn, index) => {
      btn.addEventListener("mouseenter", () => this.goTo(index));
      // 或 click 事件:btn.addEventListener("click", () => this.goTo(index));
    });
  }
  
  goTo(index) {
    if (index === this.currentIndex) return;
    if (index < 0 || index >= this.slides.length) return;
    
    // 更新按鈕狀態
    this.buttons[this.currentIndex].classList.remove("current");
    this.buttons[index].classList.add("current");
    
    // 切換圖片可見性
    this.slides[this.currentIndex].classList.remove("show");
    this.slides[index].classList.add("show");
    
    this.currentIndex = index;
  }
  
  next() { this.goTo((this.currentIndex + 1) % this.slides.length); }
  prev() { this.goTo((this.currentIndex - 1 + this.slides.length) % this.slides.length); }
  
  startAuto(interval = 3000) {
    this.stopAuto();
    this.timer = setInterval(() => this.next(), interval);
  }
  stopAuto() { clearInterval(this.timer); }
}

// 初始化
document.addEventListener("DOMContentLoaded", () => {
  new SimpleSlider(".area.mid");
});

進階升級:滑動動畫版

將「瞬間切換」升級為「平滑滑動」:

// CSS 變更
#pic_list {
  display: flex;           // 水平排列
  width: 1200px;           // 240px * 5
  transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}
#pic_list li { flex-shrink: 0; visibility: visible; } // 全部可見

// JS 變更
goTo(index) {
  this.picList.style.transform = `translateX(-${index * 240}px)`;
  // 按鈕狀態更新同前
}

觸控滑動支援

let startX = 0, startIndex = 0;

this.picList.addEventListener("touchstart", (e) => {
  startX = e.touches[0].clientX;
  startIndex = this.currentIndex;
  this.picList.style.transition = "none"; // 拖拽時取消動畫
});

this.picList.addEventListener("touchmove", (e) => {
  const deltaX = e.touches[0].clientX - startX;
  const offset = -startIndex * 240 + deltaX;
  this.picList.style.transform = `translateX(${offset}px)`;
});

this.picList.addEventListener("touchend", (e) => {
  const deltaX = e.changedTouches[0].clientX - startX;
  this.picList.style.transition = ""; // 恢復動畫
  
  if (Math.abs(deltaX) > 50) { // 閾值 50px
    this.goTo(startIndex + (deltaX < 0 ? 1 : -1));
  } else {
    this.goTo(startIndex); // 彈回
  }
});

無障礙增強

  • 按鈕改用 <button>:<button role="tab" aria-selected="true">1</button>
  • 容器添加 role="region" aria-roledescription="輪播" aria-label="產品圖片"
  • 鍵盤操作:ArrowLeft/ArrowRight 切換、Home/End 跳首尾
  • 自動播放提供暫停按鈕,符合 WCAG 2.2.2 暫停、停止、隱藏

效能優化

優化說明
圖片懶加載loading="lazy" 或 IntersectionObserver 延遲載入非首屏圖片
CSS Containment.area { contain: layout paint style; } 限制重排範圍
will-change#pic_list { will-change: transform; } 提升合成層
事件委派按鈕事件綁定在 #button 上,利用冒泡處理

總結

從「可見性切換」到「Transform 滑動」,再到「觸控支援、無障礙、效能優化」,簡易焦點圖的演進路徑折射出前端元件成熟的完整軌跡。掌握基礎邏輯後,建議實務專案直接採用 Swiper、Flickity 或 tiny-slider 等成熟庫,專注於業務創新而非重複造輪子。

copyright © 萬盛學電腦網 all rights reserved