這份腳本示範一個自製的圖片輪播:以 ul 橫向排列圖片,靠改變容器 left 值達到捲動切換,並支援自動播放、左右箭頭、下方導覽點與圖說同步。
$(function() {
var imgPro = {
imgWidth : 626, // 單張圖片寬度
imgConLength: 0, // 圖片帶總長度
index : 0, // 導覽鎖定索引
count : 0, // 圖片數量
left : 0, // 絕對定位的 left
pre : -1, // 上一張索引
curr : 0, // 目前張索引
next : 1, // 下一張索引
direction : 1, // 自動播放方向
interTime : 3000 // 輪播間隔(毫秒)
};
把這些值收在一個物件裡,是避免全域變數散落、也方便日後改成外掛設定檔的常見手法。
addImgAlt(imgPro.curr);
imgPro.count = $('#banner .list a img').length;
imgPro.imgConLength = imgPro.imgWidth * imgPro.count;
imgPro.left = parseInt($('#box .list ul').css("left"));
// 播放定時器
var t = setInterval(imgPlay, imgPro.interTime);
// 滑入互動區暫停,滑出恢復
$('#box .arrowl img, #box .arrowr img, #banner .list a, #box .count li, #box p')
.hover(function () { clearInterval(t); },
function () { t = setInterval(imgPlay, imgPro.interTime); });
function imgPlay() {
if ((imgPro.next != imgPro.count && imgPro.direction == 1) ||
(imgPro.pre == -1 && imgPro.direction == -1)) {
imgPro.direction = 1;
toNext();
} else {
imgPro.direction = -1;
toLast();
}
}
這段邏輯讓輪播在抵達頭尾時自動折返,形成來回播放的效果,而不是硬跳回第一張。
// 點擊左箭頭
$('#box .arrowl img').click(function () {
if (imgPro.curr != 0) { toLast(); }
});
// 點擊右箭頭
$('#box .arrowr img').click(function () {
if (imgPro.next != imgPro.count) { toNext(); }
});
// 點擊導覽點直接跳到該張
$('#box .count li').click(function () {
imgPro.index = $('#box .count li').index(this);
if (imgPro.curr != imgPro.index) {
imgPro.left += (imgPro.curr - imgPro.index) * imgPro.imgWidth;
addImgAlt(imgPro.index);
play();
$('#box .count li').eq(imgPro.curr).removeClass('current')
.end().eq(imgPro.index).addClass('current');
imgPro.curr = imgPro.index;
imgPro.pre = imgPro.index - 1;
imgPro.next = imgPro.index + 1;
}
});
function play() {
$('#box .list ul').css({ 'opacity': '0.5' }).animate({
'left': imgPro.left + "px",
'opacity': '1'
}, 'slow');
}
// 讀取圖片 alt 當作圖說
function addImgAlt(index) {
$("#box p").text($("#banner .list a img").eq(index).attr("alt"));
}
function toLast() {
imgPro.left += imgPro.imgWidth;
addImgAlt(imgPro.pre);
play();
$('#box .count li').eq(imgPro.curr).removeClass('current')
.end().eq(imgPro.pre).addClass('current');
imgPro.pre--; imgPro.curr--; imgPro.next--;
}
function toNext() {
imgPro.left -= imgPro.imgWidth;
addImgAlt(imgPro.next);
play();
$('#box .count li').eq(imgPro.curr).removeClass('current')
.end().eq(imgPro.next).addClass('current');
imgPro.pre++; imgPro.curr++; imgPro.next++;
}
});
alt 屬性,省下一份獨立的文字資料,也對 SEO 與無障礙友善。animate 前先把 opacity 降到 0.5,動畫結束回到 1,能減弱切換時的突兀感。curr 同步,讓箭頭與自動播放共用同一套狀態,不必另寫分支。toLast/toNext 的邊界判斷改為取模數運算即可。