圖片輪播是網頁常見元件。本文示範使用 jQuery 打造支援「自動輪播」、「指示器點擊切換」、「滑鼠懸停暫停」的響應式輪播器,核心邏輯約 60 行,易於擴充客製化。
<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>
.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; }
$(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();
});
常見做法:在圖片序列首尾各複製一張 (共 6 張),動畫到複製的第一張時瞬間重置 left 到真正第一張位置,實現視覺無縫循環。本範例為簡化示範,採用動畫回調瞬移方式。
.stop() 清除動畫佇列防止快速點擊疊加;.animate() 使用 CSS left 位移而非 transform,配合 jQuery 動畫引擎較穩定。
指示器 hover 同時處理「暫停自動播放」、「立即跳轉」、「恢復自動播放」,確保狀態一致。
touchstart/move/end 計算位移切換。resize 重新計算 imgWidth 並重設位置。data-src + IntersectionObserver 載入可視區圖片。aria-label、鍵盤左右鍵切換、role="region"。| 現象 | 可能原因 | 解決方案 |
|---|---|---|
| 圖片跳動/留白 | 圖片未設定 display:block 或 flex-shrink:0 | CSS 強制尺寸、移除行內間隙 |
| 指示器不同步 | 索引計算錯誤 (0-based vs 1-based) | 統一用 0-based 內部索引,顯示時 +1 |
| 自動播放不停止 | 多重 timer 未清除 | 統一變數管理 timer,切換前必清除 |
掌握「定位容器 + 位移動畫 + 狀態機」三要素即可自寫輪播器。本範例展示核心邏輯,實際專案建議封裝為可複用 Plugin 或採用成熟庫 (Swiper, Slick, Flickity) 以支援更豐富功能與邊界情況。