水平輪播本質是:
overflow: hiddenposition: absolute; left: 0left 或 transform: translateX() 實現滑動<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>
.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; }
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
});
});
| 方案 | 原文 | 現代最佳實踐 |
|---|---|---|
| 動畫屬性 | left | transform: 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" 或 IntersectionObserverrequestAnimationFramedestroy() 釋放記憶體輪播圖是前端基礎元件,核心在於「軌道位移 + 狀態同步」。原文使用 left + float 屬於 jQuery 時代典型寫法;現代開發應採用 Flexbox + Transform + CSS Transition,配合 transitionend 事件實現無縫循環,並封裝為可複用類別。本文提供從基礎版到進階無縫循環的完整演進代碼,適合不同專案需求直接採用。