無縫輪播 (Seamless Carousel) 是展示型網站常見元件。核心原理:複製首尾項目形成閉環,利用位移動畫並在邊界瞬時重置位置。本文提供原生 JS 完整實作,含滑鼠暫停、方向控制、觸控滑動、IntersectionObserver 可見性優化。
原始項目:[1] [2] [3] [4]
複製首尾:[4] [1] [2] [3] [4] [1]
↑ ↑
重置點 重置點
向左滾動:位移從 0 → -100% → 瞬間跳回 0 (視覺無縫)
向右滾動:位移從 -100% → 0 → 瞬間跳回 -100%
<div class="carousel" id="carousel">
<button class="carousel__btn carousel__btn--prev" aria-label="上一張">‹</button>
<div class="carousel__viewport">
<ul class="carousel__track" id="track">
<li class="carousel__slide"><img src="img/1.jpg" alt="圖片1"></li>
<li class="carousel__slide"><img src="img/2.jpg" alt="圖片2"></li>
<li class="carousel__slide"><img src="img/3.jpg" alt="圖片3"></li>
<li class="carousel__slide"><img src="img/4.jpg" alt="圖片4"></li>
</ul>
</div>
<button class="carousel__btn carousel__btn--next" aria-label="下一張">›</button>
<div class="carousel__dots" aria-label="輪播指示器"></div>
</div>
.carousel { position: relative; overflow: hidden; }
.carousel__viewport { overflow: hidden; }
.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%;
width: 100%;
}
.carousel__slide img { width: 100%; height: auto; display: block; }
.carousel__btn {
position: absolute; top: 50%; transform: translateY(-50%);
background: rgba(0,0,0,0.5); color: white; border: none;
width: 40px; height: 40px; border-radius: 50%; cursor: pointer;
}
.carousel__btn--prev { left: 12px; }
.carousel__btn--next { right: 12px; }
.carousel__dots { display: flex; gap: 8px; justify-content: center; padding: 12px; }
.carousel__dot {
width: 10px; height: 10px; border-radius: 50%; background: rgba(255,255,255,0.5);
border: none; cursor: pointer; transition: background 0.2s;
}
.carousel__dot.active { background: white; }
class SeamlessCarousel {
constructor(selector, options = {}) {
this.root = document.querySelector(selector);
if (!this.root) throw new Error('Carousel container not found');
this.track = this.root.querySelector('.carousel__track');
this.slides = Array.from(this.track.children);
this.prevBtn = this.root.querySelector('.carousel__btn--prev');
this.nextBtn = this.root.querySelector('.carousel__btn--next');
this.dotsContainer = this.root.querySelector('.carousel__dots');
this.options = {
autoplay: options.autoplay !== false,
interval: options.interval || 3000,
speed: options.speed || 500,
pauseOnHover: options.pauseOnHover !== false,
direction: options.direction || 'left', // 'left' | 'right'
...options
};
this.currentIndex = 0;
this.slideWidth = 0;
this.timer = null;
this.isAnimating = false;
this.touchStartX = 0;
this.init();
}
init() {
this.cloneSlides();
this.createDots();
this.bindEvents();
this.resize();
if (this.options.autoplay) this.startAutoplay();
// 可見性優化:離開頁面暫停
document.addEventListener('visibilitychange', () => {
document.hidden ? this.stopAutoplay() : this.startAutoplay();
});
}
cloneSlides() {
// 複製首尾各一組 (或多組視需求)
const firstClone = this.slides[0].cloneNode(true);
const lastClone = this.slides[this.slides.length - 1].cloneNode(true);
firstClone.dataset.clone = 'first';
lastClone.dataset.clone = 'last';
this.track.appendChild(firstClone);
this.track.insertBefore(lastClone, this.slides[0]);
// 更新 slides 參考 (現在包含複製項)
this.allSlides = Array.from(this.track.children);
this.totalSlides = this.slides.length; // 原始數量
}
createDots() {
if (!this.dotsContainer) return;
this.dotsContainer.innerHTML = this.slides.map((_, i) =>
``
).join('');
this.dots = Array.from(this.dotsContainer.children);
}
bindEvents() {
// 按鈕
this.prevBtn?.addEventListener('click', () => this.prev());
this.nextBtn?.addEventListener('click', () => this.next());
// 指示器
this.dotsContainer?.addEventListener('click', e => {
const dot = e.target.closest('.carousel__dot');
if (dot) this.goTo(parseInt(dot.dataset.index));
});
// 滑鼠懸停暫停
if (this.options.pauseOnHover) {
this.root.addEventListener('mouseenter', () => this.stopAutoplay());
this.root.addEventListener('mouseleave', () => this.startAutoplay());
}
// 觸控滑動
this.track.addEventListener('touchstart', e => this.onTouchStart(e), { passive: true });
this.track.addEventListener('touchmove', e => this.onTouchMove(e), { passive: false });
this.track.addEventListener('touchend', e => this.onTouchEnd(e));
// 視窗大小變化
window.addEventListener('resize', () => this.resize());
// 鍵盤支援
this.root.addEventListener('keydown', e => {
if (e.key === 'ArrowLeft') this.prev();
if (e.key === 'ArrowRight') this.next();
});
}
resize() {
this.slideWidth = this.root.offsetWidth;
// 重新定位到當前索引 (不動畫)
this.track.style.transition = 'none';
this.setPosition(-this.slideWidth * (this.currentIndex + 1));
// 強制重繪
this.track.offsetHeight;
this.track.style.transition = `transform ${this.options.speed}ms cubic-bezier(0.4, 0, 0.2, 1)`;
}
setPosition(x) {
this.track.style.transform = `translateX(${x}px)`;
}
goTo(index) {
if (this.isAnimating) return;
this.currentIndex = (index + this.totalSlides) % this.totalSlides;
this.moveToIndex(this.currentIndex);
this.updateDots();
}
next() { this.goTo(this.currentIndex + 1); }
prev() { this.goTo(this.currentIndex - 1); }
moveToIndex(index) {
this.isAnimating = true;
const targetX = -this.slideWidth * (index + 1); // +1 因為前面有複製的最後一張
this.setPosition(targetX);
// 動畫結束後檢查是否需重置
setTimeout(() => {
this.checkBoundaryReset(index);
this.isAnimating = false;
}, this.options.speed);
}
checkBoundaryReset(index) {
// 到達複製的第一張 (索引 totalSlides) → 瞬間跳回真正第一張 (索引 0)
if (index === this.totalSlides) {
this.track.style.transition = 'none';
this.currentIndex = 0;
this.setPosition(-this.slideWidth);
this.track.offsetHeight; // 強制重繪
this.track.style.transition = `transform ${this.options.speed}ms cubic-bezier(0.4, 0, 0.2, 1)`;
}
// 到達複製的最後一張 (索引 -1) → 瞬間跳回真正最後一張
else if (index === -1) {
this.track.style.transition = 'none';
this.currentIndex = this.totalSlides - 1;
this.setPosition(-this.slideWidth * this.totalSlides);
this.track.offsetHeight;
this.track.style.transition = `transform ${this.options.speed}ms cubic-bezier(0.4, 0, 0.2, 1)`;
}
}
updateDots() {
this.dots?.forEach((dot, i) => {
dot.classList.toggle('active', i === this.currentIndex);
});
}
// 觸控處理
onTouchStart(e) {
this.touchStartX = e.touches[0].clientX;
this.stopAutoplay();
}
onTouchMove(e) {
if (this.isAnimating) return;
const deltaX = e.touches[0].clientX - this.touchStartX;
// 即時跟隨手指 (不動畫)
this.track.style.transition = 'none';
this.setPosition(-this.slideWidth * (this.currentIndex + 1) + deltaX);
}
onTouchEnd(e) {
const deltaX = e.changedTouches[0].clientX - this.touchStartX;
this.track.style.transition = `transform ${this.options.speed}ms cubic-bezier(0.4, 0, 0.2, 1)`;
if (Math.abs(deltaX) > this.slideWidth * 0.15) { // 閾值 15%
deltaX > 0 ? this.prev() : this.next();
} else {
this.moveToIndex(this.currentIndex); // 彈回
}
this.startAutoplay();
}
startAutoplay() {
this.stopAutoplay();
this.timer = setInterval(() => {
this.options.direction === 'left' ? this.next() : this.prev();
}, this.options.interval);
}
stopAutoplay() { clearInterval(this.timer); }
destroy() {
this.stopAutoplay();
window.removeEventListener('resize', this.resize);
document.removeEventListener('visibilitychange', this.visibilityHandler);
// 移除複製項
this.track.querySelectorAll('[data-clone]').forEach(el => el.remove());
this.root.removeEventListener('keydown', this.keyHandler);
}
}
// 初始化
const carousel = new SeamlessCarousel('#carousel', {
autoplay: true,
interval: 3000,
speed: 500,
direction: 'left'
});
{ passive: true } 提升滾動效能aria-label 按鈕、指示器aria-roledescription="carousel" 容器@media (prefers-reduced-motion: reduce) 關閉自動播放無縫輪播核心在於「複製首尾形成閉環 + 邊界瞬時重置」。原生 JS 實作可完全控制細節、零依賴、效能最優。生產環境建議封裝為 Web Component (<seamless-carousel>) 實現框架無關復用。