本文實作一款經典的 jQuery 圖片輪播器,支援左右按鈕切換、圓點指示器、自動播放與滑鼠懸停暫停,採用絕對定位配合 animate() 實現平滑滑動過渡。
.lxfscroll:固定寬高、overflow: hidden、position: relativeul > li:絕對定位疊放,寬高同容器.button:包含上一張/下一張按鈕與當前頁碼顯示$(function() {
var $li = $(".lxfscroll li");
var len = $li.length;
var index = 0;
var speed = 300;
var timer;
// 初始佈局:第一張顯示,其餘分居左右兩側
$li.not(":first").css({ left: "400px" });
$li.eq(len - 1).css({ left: "-400px" });
// 核心切換函數
function goto(targetIndex) {
if ($li.is(":animated")) return; // 防止連點
var current = $li.eq(index);
var next = $li.eq(targetIndex);
var direction = targetIndex > index ? "next" : "prev";
// 設置進場位置
next.css({ left: direction === "next" ? "400px" : "-400px" });
// 動畫執行
current.animate({ left: direction === "next" ? "-400px" : "400px" }, speed);
next.animate({ left: "0px" }, speed, function() {
// 重置非當前圖片位置
$li.not(next).css({ left: direction === "next" ? "400px" : "-400px" });
});
index = targetIndex;
updateIndicator();
}
// 指示器同步
function updateIndicator() {
$(".button i").text(index + 1);
}
// 事件綁定
$("input[value='下一個']").click(function() {
goto(index >= len - 1 ? 0 : index + 1);
});
$("input[value='上一個']").click(function() {
goto(index <= 0 ? len - 1 : index - 1);
});
// 自動播放
function autoPlay() {
timer = setInterval(function() {
goto(index >= len - 1 ? 0 : index + 1);
}, 3000);
}
autoPlay();
// 滑鼠懸停暫停
$(".lxfscroll").hover(
function() { clearInterval(timer); },
function() { autoPlay(); }
);
});
.lxfscroll {
width: 400px;
height: 300px;
margin: 20px auto;
overflow: hidden;
position: relative;
border: 1px dashed #ccc;
}
.lxfscroll ul li {
position: absolute;
top: 0;
width: 400px;
height: 300px;
text-align: center;
line-height: 300px;
font-size: 40px;
font-weight: bold;
}
.button {
width: 400px;
margin: 10px auto;
text-align: center;
}
.button input {
padding: 4px 12px;
}
.button i {
color: #f00;
font-weight: bold;
}
| 改良項目 | 說明 |
|---|---|
| 觸控支援 | 加入 touchstart/touchmove/touchend 實現手機滑動切換 |
| 響應式適配 | 使用百分比寬度 + max-width,配合 object-fit: cover 處理圖片 |
| 無障礙增強 | 添加 role="region"、aria-roledescription="輪播"、鍵盤左右鍵操作 |
| 效能優化 | 圖片懶加載(loading="lazy")、將 animate 改為 CSS transition + transform 開啟 GPU 加速 |
| 程式碼模組化 | 封裝為 jQuery Plugin 或 ES6 Class,支援多實例、配置選項(速度、自動播放間隔、循環模式) |
此輪播器展示了 jQuery 操作 DOM 位置與動畫的經典模式。雖然現代專案常改用 Swiper、Slick 等成熟庫,但理解原生實作邏輯有助於除錯與客製化開發。建議實務專案中根據複雜度,權衡自行實作與引入庫的利弊。