萬盛學電腦網

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

jQuery 實作響應式左右輪播圖 (Carousel):完整原理與代碼解析

輪播圖核心原理

水平輪播本質是:

  1. 容器:固定寬高、overflow: hidden
  2. 軌道:寬度 = 單張寬度 × 數量,position: absolute; left: 0
  3. 滑塊:並排浮動/彈性排版,每張寬度 = 容器寬度
  4. 動畫:改變軌道 left 或 transform: translateX() 實現滑動
  5. 循環:首尾複製首尾項,到達邊界時瞬移回對應位置
  6. 指示器/箭頭:控制當前索引,同步更新視覺狀態

完整實作代碼 (現代化重構版)

HTML 結構

<div id="carousel" class="carousel">
  <div class="carousel-track">
    <div class="carousel-slide"><img src="img/1.jpg" alt="輪播 1"></div>
    <div class="carousel-slide"><img src="img/2.jpg" alt="輪播 2"></div>
    <div class="carousel-slide"><img src="img/3.jpg" alt="輪播 3"></div>
    <div class="carousel-slide"><img src="img/4.jpg" alt="輪播 4"></div>
    <div class="carousel-slide"><img src="img/5.jpg" alt="輪播 5"></div>
  </div>
  
  <button class="carousel-arrow prev" aria-label="上一張">‹</button>
  <button class="carousel-arrow next" aria-label="下一張">›</button>
  
  <nav class="carousel-dots" aria-label="輪播導航">
    <button class="dot active" data-index="0" aria-label="第 1 張"></button>
    <button class="dot" data-index="1" aria-label="第 2 張"></button>
    <button class="dot" data-index="2" aria-label="第 3 張"></button>
    <button class="dot" data-index="3" aria-label="第 4 張"></button>
    <button class="dot" data-index="4" aria-label="第 5 張"></button>
  </nav>
</div>

CSS 樣式 (關鍵:Flex + Transform)

.carousel {
  position: relative;
  width: 100%; max-width: 1000px;
  margin: 0 auto;
  overflow: hidden;
  border-radius: 8px;
  background: #f0f0f0;
}
.carousel-track {
  display: flex;
  transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
  will-change: transform;
}
.carousel-slide {
  flex: 0 0 100%;  /* 每張佔滿容器寬度 */
  min-width: 0;    /* 防止 flex 縮小 */
}
.carousel-slide img {
  width: 100%; height: auto; display: block;
}
.carousel-arrow {
  position: absolute; top: 50%; transform: translateY(-50%);
  width: 44px; height: 44px;
  background: rgba(0,0,0,0.4); color: white;
  border: none; border-radius: 50%;
  font-size: 24px; line-height: 1;
  cursor: pointer; z-index: 10;
  transition: background 0.2s;
}
.carousel-arrow:hover { background: rgba(0,0,0,0.7); }
.carousel-arrow.prev { left: 16px; }
.carousel-arrow.next { right: 16px; }
.carousel-dots {
  position: absolute; bottom: 16px; left: 50%; transform: translateX(-50%);
  display: flex; gap: 8px; z-index: 10;
}
.dot {
  width: 10px; height: 10px; border-radius: 50%;
  background: rgba(255,255,255,0.6); border: none;
  cursor: pointer; transition: all 0.2s;
}
.dot.active { background: white; transform: scale(1.2); }
.dot:hover { background: white; }

jQuery 核心邏輯 (ES6 類別封裝)

class Carousel {
  constructor(selector, options = {}) {
    this.$el = $(selector);
    this.$track = this.$el.find('.carousel-track');
    this.$slides = this.$track.children('.carousel-slide');
    this.$dots = this.$el.find('.dot');
    this.$prev = this.$el.find('.prev');
    this.$next = this.$el.find('.next');
    
    this.count = this.$slides.length;
    this.current = 0;
    this.animating = false;
    this.autoTimer = null;
    
    this.options = $.extend({
      autoPlay: true,
      interval: 3000,
      speed: 500,
      pauseOnHover: true,
      loop: true
    }, options);
    
    this.init();
  }
  
  init() {
    this.bindEvents();
    if (this.options.autoPlay) this.startAutoPlay();
    this.updateDots();
  }
  
  bindEvents() {
    this.$next.on('click', () => this.next());
    this.$prev.on('click', () => this.prev());
    this.$dots.on('click', (e) => this.goTo($(e.currentTarget).data('index')));
    
    if (this.options.pauseOnHover) {
      this.$el.on('mouseenter', () => this.stopAutoPlay())
               .on('mouseleave', () => this.startAutoPlay());
    }
    
    // 鍵盤支援
    $(document).on('keydown', (e) => {
      if (this.$el.is(':hover')) {
        if (e.key === 'ArrowLeft') this.prev();
        if (e.key === 'ArrowRight') this.next();
      }
    });
    
    // 觸控滑動支援
    this.enableTouchSwipe();
  }
  
  enableTouchSwipe() {
    let startX = 0;
    this.$el.on('touchstart', (e) => { startX = e.originalEvent.touches[0].clientX; });
    this.$el.on('touchend', (e) => {
      let endX = e.originalEvent.changedTouches[0].clientX;
      let diff = startX - endX;
      if (Math.abs(diff) > 50) {
        diff > 0 ? this.next() : this.prev();
      }
    });
  }
  
  goTo(index) {
    if (this.animating || index === this.current) return;
    this.animating = true;
    this.current = index;
    this.animateTrack();
    this.updateDots();
    setTimeout(() => this.animating = false, this.options.speed);
  }
  
  next() {
    let nextIndex = this.current + 1;
    if (nextIndex >= this.count) {
      if (this.options.loop) nextIndex = 0;
      else return;
    }
    this.goTo(nextIndex);
  }
  
  prev() {
    let prevIndex = this.current - 1;
    if (prevIndex < 0) {
      if (this.options.loop) prevIndex = this.count - 1;
      else return;
    }
    this.goTo(prevIndex);
  }
  
  animateTrack() {
    // 使用 transform 而非 left:GPU 加速、不觸發重排
    this.$track.css('transform', `translateX(-${this.current * 100}%)`);
  }
  
  updateDots() {
    this.$dots.removeClass('active').eq(this.current).addClass('active');
  }
  
  startAutoPlay() {
    this.stopAutoPlay();
    this.autoTimer = setInterval(() => this.next(), this.options.interval);
  }
  
  stopAutoPlay() {
    clearInterval(this.autoTimer);
    this.autoTimer = null;
  }
  
  destroy() {
    this.stopAutoPlay();
    this.$el.off();
    $(document).off('keydown');
  }
}

// 初始化
$(function() {
  window.myCarousel = new Carousel('#carousel', {
    autoPlay: true,
    interval: 4000,
    speed: 600
  });
});

關鍵技術點對比

方案原文現代最佳實踐
動畫屬性lefttransform: translateX() (GPU 加速)
佈局float + 絕對定位Flexbox (簡單、響應式)
循環邏輯瞬移 left複製首尾節點 + 無縫循環 (進階)
觸控支援無touchstart/touchend 滑動檢測
無障礙無ARIA、鍵盤、語意化標籤
程式碼組織全域函式ES6 Class 封裝、可多實例

無縫循環進階實作 (複製首尾節點法)

// 初始化時複製首尾
init() {
  // ... 
  if (this.options.loop && this.count > 1) {
    this.$track.prepend(this.$slides.last().clone().addClass('clone'));
    this.$track.append(this.$slides.first().clone().addClass('clone'));
    this.$slides = this.$track.children('.carousel-slide');  // 重新獲取含複製項
    this.count = this.$slides.length;
    this.current = 1;  // 從第一個真實項開始
    this.$track.css('transform', `translateX(-${this.current * 100}%)`);
  }
}

// 動畫結束檢查 (transitionend 事件)
this.$track.on('transitionend', () => {
  if (this.current === 0) {  // 到達複製的最後一項
    this.current = this.count - 2;
    this.$track.css('transition', 'none').css('transform', `translateX(-${this.current * 100}%)`);
    // 強制重排
    this.$track[0].offsetHeight;
    this.$track.css('transition', '');
  } else if (this.current === this.count - 1) {  // 到達複製的第一項
    this.current = 1;
    this.$track.css('transition', 'none').css('transform', `translateX(-${this.current * 100}%)`);
    this.$track[0].offsetHeight;
    this.$track.css('transition', '');
  }
  this.updateDots();
  this.animating = false;
});

效能優化建議

  • 圖片懶載入:loading="lazy" 或 IntersectionObserver
  • will-change: transform:提升合成層
  • 避免佈局抖動:讀寫分離、使用 requestAnimationFrame
  • 銷毀清理:SPA 路由切換時呼叫 destroy() 釋放記憶體

總結

輪播圖是前端基礎元件,核心在於「軌道位移 + 狀態同步」。原文使用 left + float 屬於 jQuery 時代典型寫法;現代開發應採用 Flexbox + Transform + CSS Transition,配合 transitionend 事件實現無縫循環,並封裝為可複用類別。本文提供從基礎版到進階無縫循環的完整演進代碼,適合不同專案需求直接採用。

copyright © 萬盛學電腦網 all rights reserved