萬盛學電腦網

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

jQuery 實現簡潔圖片輪播 (Carousel) 效果完整教學

前言

圖片輪播是網頁常見元件。本文示範使用 jQuery 打造支援「自動輪播」、「指示器點擊切換」、「滑鼠懸停暫停」的響應式輪播器,核心邏輯約 60 行,易於擴充客製化。

HTML 結構

<div class="carousel">
  <div class="imgBox">
    <img src="img1.jpg" alt="圖1">
    <img src="img2.jpg" alt="圖2">
    <img src="img3.jpg" alt="圖3">
    <img src="img4.jpg" alt="圖4">
  </div>
  <ul class="imgNum">
    <li class="mark-color"></li><li></li><li></li><li></li>
  </ul>
</div>

CSS 關鍵樣式

.carousel { position: relative; width: 300px; height: 300px; overflow: hidden; margin: 0 auto; }
.imgBox { position: absolute; left: 0; top: 0; width: 1200px; height: 300px; display: flex; transition: left 1.1s; }
.imgBox img { width: 300px; height: 300px; flex-shrink: 0; }
.imgNum { position: absolute; bottom: 15px; left: 50%; transform: translateX(-50%); display: flex; gap: 8px; z-index: 1; }
.imgNum li { width: 12px; height: 12px; border-radius: 50%; background: rgba(255,255,255,0.6); cursor: pointer; }
.imgNum li.mark-color { background: #fff; }

jQuery 核心邏輯

$(function() {
  const $imgBox = $('.imgBox');
  const $dots = $('.imgNum li');
  const total = 4;           // 圖片總數
  const imgWidth = 300;      // 單張寬度
  const moveTime = 1100;     // 切換動畫 ms
  const pauseTime = 2500;    // 自動輪播間隔 ms
  let index = 1;             // 當前顯示第幾張 (1-based)
  let timer = null;

  // 移動到指定索引
  function moveTo(i) {
    if (i < 1 || i > total) return;
    $imgBox.stop().animate({ left: -(i * imgWidth) }, moveTime);
    $dots.removeClass('mark-color').eq(i - 1).addClass('mark-color');
    index = i;
  }

  // 自動輪播邏輯
  function autoPlay() {
    timer = setInterval(() => {
      if (index === total) {
        // 最後一張跳回第一張 (無縫銜接需 CSS 配合或瞬移)
        $imgBox.animate({ left: 0 }, moveTime, () => {
          $imgBox.css('left', -imgWidth); // 瞬移回第一張視覺位置
        });
        index = 1;
      } else {
        index++;
        $imgBox.animate({ left: -(index * imgWidth) }, moveTime);
      }
      $dots.removeClass('mark-color').eq(index - 1).addClass('mark-color');
    }, pauseTime);
  }

  // 指示器點擊/懸停
  $dots.hover(function() {
    clearInterval(timer);
    $imgBox.stop();
    const i = $(this).index() + 1;
    moveTo(i);
  }, function() {
    autoPlay();
  });

  // 初始化
  autoPlay();
});

關鍵技術點解析

1. 無縫循環輪播

常見做法:在圖片序列首尾各複製一張 (共 6 張),動畫到複製的第一張時瞬間重置 left 到真正第一張位置,實現視覺無縫循環。本範例為簡化示範,採用動畫回調瞬移方式。

2. 動畫佇列控制

.stop() 清除動畫佇列防止快速點擊疊加;.animate() 使用 CSS left 位移而非 transform,配合 jQuery 動畫引擎較穩定。

3. 防抖與狀態同步

指示器 hover 同時處理「暫停自動播放」、「立即跳轉」、「恢復自動播放」,確保狀態一致。

進階擴充建議

  • 觸控滑動支援:綁定 touchstart/move/end 計算位移切換。
  • 響應式適配:監聽 resize 重新計算 imgWidth 並重設位置。
  • 懶加載圖片:data-src + IntersectionObserver 載入可視區圖片。
  • 無障礙:加入 aria-label、鍵盤左右鍵切換、role="region"。

常見問題排查

現象可能原因解決方案
圖片跳動/留白圖片未設定 display:block 或 flex-shrink:0CSS 強制尺寸、移除行內間隙
指示器不同步索引計算錯誤 (0-based vs 1-based)統一用 0-based 內部索引,顯示時 +1
自動播放不停止多重 timer 未清除統一變數管理 timer,切換前必清除

總結

掌握「定位容器 + 位移動畫 + 狀態機」三要素即可自寫輪播器。本範例展示核心邏輯,實際專案建議封裝為可複用 Plugin 或採用成熟庫 (Swiper, Slick, Flickity) 以支援更豐富功能與邊界情況。

copyright © 萬盛學電腦網 all rights reserved