分頁指示器 (Pagination Dots/Indicators) 圖片輪播是行動裝置 Web App、產品展示、橫幅廣告的經典 UI 模式。本文實作一個功能完整、觸控友善、可無限循環、支援鍵盤操作的 jQuery 輪播元件。
<div class="carousel" id="my-carousel">
<div class="carousel-viewport">
<ul class="carousel-track">
<li class="carousel-slide"><img src="img1.jpg" alt="幻燈片 1"></li>
<li class="carousel-slide"><img src="img2.jpg" alt="幻燈片 2"></li>
<li class="carousel-slide"><img src="img3.jpg" alt="幻燈片 3"></li>
<li class="carousel-slide"><img src="img4.jpg" alt="幻燈片 4"></li>
</ul>
</div>
<!-- 導航按鈕 -->
<button type="button" class="carousel-btn carousel-prev" aria-label="上一張">‹</button>
<button type="button" class="carousel-btn carousel-next" aria-label="下一張">›</button>
<!-- 分頁指示器 -->
<nav class="carousel-indicators" aria-label="幻燈片導航">
<button type="button" class="indicator" data-index="0" aria-label="第 1 張"></button>
<button type="button" class="indicator" data-index="1" aria-label="第 2 張"></button>
<button type="button" class="indicator" data-index="2" aria-label="第 3 張"></button>
<button type="button" class="indicator" data-index="3" aria-label="第 4 張"></button>
</nav>
</div>
.carousel {
position: relative;
overflow: hidden;
width: 100%;
max-width: 800px;
margin: 0 auto;
background: #f5f5f5;
border-radius: 8px;
}
.carousel-viewport {
overflow: hidden;
position: relative;
}
.carousel-track {
display: flex;
transition: transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
will-change: transform;
}
.carousel-slide {
flex: 0 0 100%; /* 每張佔滿視口 */
min-width: 0; // 修正 flex 縮放問題
}
.carousel-slide img {
width: 100%;
height: auto;
display: block;
}
.carousel-btn {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 44px; height: 44px;
background: rgba(255,255,255,0.9);
border: none;
border-radius: 50%;
font-size: 24px;
cursor: pointer;
box-shadow: 0 2px 8px rgba(0,0,0,0.15);
transition: background 0.2s, transform 0.2s;
z-index: 10;
}
.carousel-btn:hover { background: white; transform: translateY(-50%) scale(1.1); }
.carousel-prev { left: 16px; }
.carousel-next { right: 16px; }
.carousel-indicators {
display: flex;
justify-content: center;
gap: 8px;
padding: 16px 0;
}
.indicator {
width: 10px; height: 10px;
border-radius: 50%;
border: none;
background: rgba(0,0,0,0.3);
cursor: pointer;
transition: background 0.2s, transform 0.2s;
}
.indicator:hover { background: rgba(0,0,0,0.6); transform: scale(1.2); }
.indicator.active { background: #007bff; transform: scale(1.3); }
;(function($) {
$.fn.carousel = function(options) {
const settings = $.extend({
interval: 4000, // 自動輪播間隔 (ms),0 或 false 關閉
animation: 'slide', // 'slide' | 'fade'
duration: 500, // 動畫時長
easing: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
pauseOnHover: true, // 懸停暫停
swipe: true, // 觸控滑動
keyboard: true, // 鍵盤控制
loop: true, // 無限循環
indicators: true, // 顯示指示器
controls: true, // 顯示上下按鈕
onSlide: null, // 切換前回呼: function(index, $slide)
onSlid: null // 切換後回呼: function(index, $slide)
}, options);
return this.each(function() {
const $carousel = $(this);
const $track = $carousel.find('.carousel-track');
const $slides = $track.children('.carousel-slide');
const $indicators = $carousel.find('.carousel-indicators');
const $prevBtn = $carousel.find('.carousel-prev');
const $nextBtn = $carousel.find('.carousel-next');
const slideCount = $slides.length;
if (slideCount <= 1) return; // 單張不需輪播
let currentIndex = 0;
let intervalTimer = null;
let isAnimating = false;
let touchStartX = 0;
// 初始化指示器
function initIndicators() {
if (!settings.indicators) return;
$indicators.empty();
for (let i = 0; i < slideCount; i++) {
$indicators.append(
``
);
}
updateIndicators();
}
function updateIndicators() {
$indicators.find('.indicator')
.removeClass('active')
.eq(currentIndex).addClass('active')
.attr('aria-current', 'true')
.siblings().removeAttr('aria-current');
}
// 核心切換邏輯
function goTo(index, direction = 'next') {
if (isAnimating) return;
isAnimating = true;
// 處理循環邊界
if (index < 0) index = settings.loop ? slideCount - 1 : 0;
if (index >= slideCount) index = settings.loop ? 0 : slideCount - 1;
if (index === currentIndex) { isAnimating = false; return; }
const $currentSlide = $slides.eq(currentIndex);
const $nextSlide = $slides.eq(index);
// 回呼:切換前
if ($.isFunction(settings.onSlide)) settings.onSlide(index, $nextSlide);
if (settings.animation === 'fade') {
// 淡入淡出模式
$nextSlide.css({ position: 'absolute', top: 0, left: 0, width: '100%', opacity: 0, zIndex: 10 });
$currentSlide.css('zIndex', 5);
$nextSlide.animate({ opacity: 1 }, settings.duration, settings.easing, () => {
$currentSlide.css({ position: '', zIndex: '' });
$nextSlide.css({ position: '', zIndex: '' });
finishSlide(index);
});
} else {
// 滑動模式 (預設)
const translateX = -index * 100;
$track.css({
transition: `transform ${settings.duration}ms ${settings.easing}`,
transform: `translateX(${translateX}%)`
});
// 使用 transitionend 事件檢測動畫結束
const onTransitionEnd = () => {
$track.off('transitionend', onTransitionEnd);
finishSlide(index);
};
$track.on('transitionend', onTransitionEnd);
// 保險:防止 transitionend 不觸發
setTimeout(onTransitionEnd, settings.duration + 100);
}
currentIndex = index;
updateIndicators();
}
function finishSlide(index) {
isAnimating = false;
if ($.isFunction(settings.onSlid)) settings.onSlid(index, $slides.eq(index));
}
// 自動輪播
function startAutoPlay() {
if (!settings.interval) return;
stopAutoPlay();
intervalTimer = setInterval(() => goTo(currentIndex + 1, 'next'), settings.interval);
}
function stopAutoPlay() {
clearInterval(intervalTimer);
intervalTimer = null;
}
// 事件綁定
$prevBtn.on('click', () => { goTo(currentIndex - 1, 'prev'); resetAutoPlay(); });
$nextBtn.on('click', () => { goTo(currentIndex + 1, 'next'); resetAutoPlay(); });
$indicators.on('click', '.indicator', function() {
goTo($(this).data('index'), 'next');
resetAutoPlay();
});
function resetAutoPlay() {
if (settings.pauseOnHover) {
stopAutoPlay();
startAutoPlay();
}
}
// 懸停暫停
if (settings.pauseOnHover) {
$carousel.on('mouseenter', stopAutoPlay).on('mouseleave', startAutoPlay);
}
// 觸控滑動
if (settings.swipe) {
$carousel.on('touchstart', e => {
touchStartX = e.originalEvent.touches[0].clientX;
}).on('touchmove', e => {
e.preventDefault(); // 防止頁面滾動
}).on('touchend', e => {
const touchEndX = e.originalEvent.changedTouches[0].clientX;
const diff = touchStartX - touchEndX;
if (Math.abs(diff) > 50) { // 閾值 50px
goTo(currentIndex + (diff > 0 ? 1 : -1), diff > 0 ? 'next' : 'prev');
resetAutoPlay();
}
});
}
// 鍵盤控制
if (settings.keyboard) {
$(document).on('keydown.carousel', e => {
if ($carousel.is(':hover') || $carousel.find(':focus').length) {
if (e.key === 'ArrowLeft') { goTo(currentIndex - 1, 'prev'); resetAutoPlay(); }
else if (e.key === 'ArrowRight') { goTo(currentIndex + 1, 'next'); resetAutoPlay(); }
}
});
}
// 視窗縮放重排 (響應式)
$(window).on('resize', debounce(() => {
// 滑動模式下需重新計算位置 (若寬度變化導致百分比位移異常)
if (settings.animation === 'slide') {
$track.css('transition', 'none');
$track.css('transform', `translateX(${-currentIndex * 100}%)`);
// 強制重繪
$track[0].offsetHeight;
$track.css('transition', `transform ${settings.duration}ms ${settings.easing}`);
}
}, 100));
// 防抖函式
function debounce(fn, delay) {
let timer;
return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); };
}
// 公開 API
const api = {
goTo: (index) => goTo(index, 'next'),
next: () => goTo(currentIndex + 1, 'next'),
prev: () => goTo(currentIndex - 1, 'prev'),
play: startAutoPlay,
pause: stopAutoPlay,
getCurrentIndex: () => currentIndex,
getSlideCount: () => slideCount,
destroy: () => {
stopAutoPlay();
$carousel.off('.carousel');
$(document).off('.carousel');
$(window).off('resize');
}
};
$carousel.data('carousel', api);
// 初始化
initIndicators();
startAutoPlay();
});
};
})(jQuery);
$(function() {
$('#my-carousel').carousel({
interval: 5000,
animation: 'slide', // 或 'fade'
duration: 600,
pauseOnHover: true,
swipe: true,
keyboard: true,
onSlid: (index, $slide) => {
// 可埋入 GA 事件追蹤
gtag('event', 'carousel_slide', { slide_index: index });
}
});
// 程式化控制範例
const carousel = $('#my-carousel').data('carousel');
$('#go-slide-3').on('click', () => carousel.goTo(2)); // 跳到第 3 張 (索引 2)
});
aria-label、aria-current 於指示器role="region" aria-roledescription="carousel" 於容器此輪播元件核心採用 Flexbox + transform translateX 實現高效能滑動,支援淡入淡出模式、觸控滑動、鍵盤操作、無限循環、自動播放暫停、響應式重排。封裝為 jQuery Plugin 並暴露公開 API,易於整合與擴充。生產環境建議搭配圖片懶載入 (loading="lazy")、WebP 格式、CDN 加速。