無縫循環滾動、滑鼠懸停暫停、左右按鈕控制方向、支援任意張數圖片、響應式適配。
setInterval 持續更新 left 位移<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>無縫無限輪播圖片走馬燈</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { display: flex; justify-content: center; align-items: center; height: 100vh; background: #f5f5f5; font-family: sans-serif; }
.carousel-container {
width: 800px;
height: 300px;
position: relative;
overflow: hidden;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0,0,0,0.15);
background: #fff;
}
.carousel-track {
display: flex;
position: absolute;
left: 0;
top: 0;
height: 100%;
transition: left 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
will-change: transform;
}
.carousel-slide {
flex: 0 0 800px;
width: 800px;
height: 300px;
display: flex;
align-items: center;
justify-content: center;
font-size: 48px;
font-weight: bold;
color: white;
user-select: none;
}
/* 預設漸變背景示意 */
.slide-1 { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.slide-2 { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.slide-3 { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.slide-4 { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.slide-5 { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
/* 控制按鈕 */
.carousel-btn {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 50px;
height: 50px;
border: none;
border-radius: 50%;
background: rgba(255,255,255,0.9);
color: #333;
font-size: 24px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
transition: all 0.2s;
z-index: 10;
}
.carousel-btn:hover { background: white; transform: translateY(-50%) scale(1.1); box-shadow: 0 6px 20px rgba(0,0,0,0.2); }
.carousel-btn:active { transform: translateY(-50%) scale(0.95); }
.carousel-btn.prev { left: 20px; }
.carousel-btn.next { right: 20px; }
/* 指示器 */
.carousel-indicators {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 8px;
z-index: 10;
}
.indicator {
width: 12px;
height: 12px;
border-radius: 50%;
background: rgba(255,255,255,0.5);
cursor: pointer;
transition: all 0.2s;
}
.indicator.active { background: white; transform: scale(1.2); }
.indicator:hover { background: rgba(255,255,255,0.8); }
/* 響應式 */
@media (max-width: 820px) {
.carousel-container { width: 95vw; height: 35vw; max-height: 300px; }
.carousel-slide { flex-basis: 100%; width: 100%; font-size: 10vw; }
.carousel-btn { width: 40px; height: 40px; font-size: 18px; }
}
</style>
</head>
<body>
<div class="carousel-container">
<div class="carousel-track" id="track">
<!-- JS 動態生成 slides -->
</div>
<button class="carousel-btn prev" id="prevBtn" aria-label="上一張">‹</button>
<button class="carousel-btn next" id="nextBtn" aria-label="下一張">›</button>
<div class="carousel-indicators" id="indicators"></div>
</div>
<script>
(function() {
// 配置
const CONFIG = {
containerWidth: 800,
slideCount: 5,
autoPlayInterval: 3000,
transitionDuration: 500
};
// 數據 (實際專案可從 API 獲取)
const slidesData = [
{ class: 'slide-1', text: 'Slide 1' },
{ class: 'slide-2', text: 'Slide 2' },
{ class: 'slide-3', text: 'Slide 3' },
{ class: 'slide-4', text: 'Slide 4' },
{ class: 'slide-5', text: 'Slide 5' }
];
const track = document.getElementById('track');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const indicatorsContainer = document.getElementById('indicators');
let currentIndex = 0; // 0-based,對應真實幻燈片
let isAnimating = false;
let autoPlayTimer = null;
// 1. 初始化 DOM:複製首尾實現無縫
function init() {
// 複製最後一張到最前
const lastSlide = createSlide(slidesData[slidesData.length - 1], slidesData.length - 1, true);
track.insertBefore(lastSlide, track.firstChild);
// 生成真實幻燈片
slidesData.forEach((data, i) => {
track.appendChild(createSlide(data, i));
});
// 複製第一張到最後
const firstSlide = createSlide(slidesData[0], 0, true);
track.appendChild(firstSlide);
// 初始位置:顯示第一張真實幻燈片 (索引 1,因為前面插入了複製的最後一張)
track.style.left = `-${CONFIG.containerWidth}px`;
// 生成指示器
slidesData.forEach((_, i) => {
const dot = document.createElement('span');
dot.className = 'indicator' + (i === 0 ? ' active' : '');
dot.dataset.index = i;
dot.addEventListener('click', () => goToSlide(i));
indicatorsContainer.appendChild(dot);
});
// 綁定事件
prevBtn.addEventListener('click', () => navigate(-1));
nextBtn.addEventListener('click', () => navigate(1));
const container = document.querySelector('.carousel-container');
container.addEventListener('mouseenter', stopAutoPlay);
container.addEventListener('mouseleave', startAutoPlay);
// 鍵盤支援
document.addEventListener('keydown', (e) => {
if (e.key === 'ArrowLeft') navigate(-1);
if (e.key === 'ArrowRight') navigate(1);
});
// 觸控滑動支援
let touchStartX = 0;
container.addEventListener('touchstart', (e) => { touchStartX = e.touches[0].clientX; }, {passive: true});
container.addEventListener('touchend', (e) => {
const dx = e.changedTouches[0].clientX - touchStartX;
if (Math.abs(dx) > 50) navigate(dx > 0 ? -1 : 1);
}, {passive: true});
startAutoPlay();
}
function createSlide(data, index, isClone = false) {
const div = document.createElement('div');
div.className = `carousel-slide ${data.class}`;
div.textContent = data.text;
div.dataset.index = index;
div.dataset.clone = isClone;
return div;
}
function navigate(direction) {
if (isAnimating) return;
isAnimating = true;
stopAutoPlay();
const totalReal = slidesData.length;
const slideWidth = CONFIG.containerWidth;
currentIndex = (currentIndex + direction + totalReal) % totalReal;
const targetPos = -(currentIndex + 1) * slideWidth; // +1 因為前面有複製的最後一張
track.style.transition = `left ${CONFIG.transitionDuration}ms cubic-bezier(0.25, 0.46, 0.45, 0.94)`;
track.style.left = `${targetPos}px`;
updateIndicators();
// 過渡結束後檢查是否需要無縫跳轉
setTimeout(() => {
// 到達複製的第一張 (索引 totalReal) -> 跳回真實第一張 (索引 0)
if (currentIndex === 0 && track.style.left === `-${(totalReal + 1) * slideWidth}px`) {
track.style.transition = 'none';
track.style.left = `-${slideWidth}px`;
}
// 到達複製的最後一張 (索引 -1 即複製的最後一張) -> 跳回真實最後一張
if (currentIndex === totalReal - 1 && track.style.left === `0px`) {
track.style.transition = 'none';
track.style.left = `-${totalReal * slideWidth}px`;
}
isAnimating = false;
startAutoPlay();
}, CONFIG.transitionDuration);
}
function goToSlide(index) {
if (isAnimating || index === currentIndex) return;
const direction = index > currentIndex ? 1 : -1;
// 計算最短路徑 (可選優化)
navigate(direction);
}
function updateIndicators() {
document.querySelectorAll('.indicator').forEach((dot, i) => {
dot.classList.toggle('active', i === currentIndex);
});
}
function startAutoPlay() {
stopAutoPlay();
autoPlayTimer = setInterval(() => navigate(1), CONFIG.autoPlayInterval);
}
function stopAutoPlay() {
clearInterval(autoPlayTimer);
autoPlayTimer = null;
}
// 可見性 API:頁面隱藏時暫停
document.addEventListener('visibilitychange', () => {
if (document.hidden) stopAutoPlay();
else startAutoPlay();
});
init();
})();
</script>
</body>
</html>
function createSlide(data, index, isClone) {
const div = document.createElement('div');
div.className = `carousel-slide`;
div.dataset.index = index;
div.dataset.clone = isClone;
const img = document.createElement('img');
img.src = data.imageUrl; // 實際圖片 URL
img.alt = data.text;
img.loading = 'lazy'; // 原生懶加載
img.style.width = '100%';
img.style.height = '100%';
img.style.objectFit = 'cover';
div.appendChild(img);
return div;
}
.carousel-track {
/* 使用 transform 而非 left,觸發 GPU 加速 */
transform: translateX(0);
will-change: transform;
}
/* JS 中 */
track.style.transform = `translateX(${targetPos}px)`;
// 重置時
track.style.transition = 'none';
track.style.transform = `translateX(${-slideWidth}px)`;
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) startAutoPlay();
else stopAutoPlay();
});
}, { threshold: 0.1 });
observer.observe(document.querySelector('.carousel-container'));
@media (prefers-reduced-motion: reduce)@media (prefers-reduced-motion: reduce) {
.carousel-track { transition: none !important; }
.carousel-slide { animation: none !important; }
}
原生 JS 實現無縫輪播核心技巧:首尾複製節點 + 位置瞬間重置 + CSS 過渡動畫。現代最佳實踐建議:使用 transform 替代 left 觸發 GPU 加速、配合 IntersectionObserver 與 Page Visibility API 管理自動播放、遵循無障礙規範。複雜專案可考慮 Swiper、Embla Carousel、Flickity 等成熟庫。