本篇分享一個以 jQuery 實作的圖集幻燈片,左側或下方排列縮圖,點擊即可切換上方的大圖,並支援左右切換、頁碼顯示與滑動式縮圖列表。
這個範例屬於教學性質,仍有幾個可以優化的方向:
<script type="text/javascript">
var currentImage;
var currentIndex = -1;
// 顯示大圖(index 從 0 開始計數)
function showImage(index) {
$(".CounterCurrent").html(index + 1);
var len = $('#OriginalPic img').length;
// 依所在位置決定左右手勢是否顯示
if (index == len - 1) { $("#aNext").hide(); } else { $("#aNext").show(); }
if (index == 0) { $("#aPrev").hide(); } else { $("#aPrev").show(); }
if (index < $('#OriginalPic img').length) {
var indexImage = $('#OriginalPic p')[index];
// 淡出目前顯示的圖
if (currentImage) {
if (currentImage != indexImage) {
$(currentImage).css('z-index', 2);
$(currentImage).fadeOut(0, function () {
$(this).css({ 'display': 'none', 'z-index': 1 })
});
}
}
// 淡入使用者選取的圖
$(indexImage).show().css({ 'opacity': 0.4 });
$(indexImage).animate({ opacity: 1 }, { duration: 200 });
currentImage = indexImage;
currentIndex = index;
// 切換縮圖高亮
$('#ThumbPic img').removeClass('active');
$($('#ThumbPic img')[index]).addClass('active');
}
}
function ShowNext() {
var len = $('#OriginalPic img').length;
var next = currentIndex < (len - 1) ? currentIndex + 1 : 0;
showImage(next);
}
function ShowPrep() {
var len = $('#OriginalPic img').length;
var next = currentIndex == 0 ? (len - 1) : currentIndex - 1;
showImage(next);
}
$("#aNext").click(function () {
ShowNext();
if ($(".active").position().left >= 144 * 5) { $("#btnNext").click(); }
});
$("#aPrev").click(function () {
ShowPrep();
if ($(".active").position().left <= 144 * 5) { $("#btnPrev").click(); }
});
$(".OriginalPicBorder").ready(function () {
ShowNext();
$('#ThumbPic li').bind('click', function (e) {
var count = $(this).attr('rel');
showImage(parseInt(count) - 1);
});
});
</script>
程式運作的核心是 showImage() 函式:它負責更新頁碼、控制左右切換箭頭的顯示,並以淡入淡出動畫完成大圖切換,同時同步更新縮圖的高亮狀態。左右切換則透過 ShowNext() 與 ShowPrep() 循環處理,達到首尾相接的效果。
線上展示與打包下載可參考原始發佈頁提供的連結。整體而言,這是一個結構清楚、易於二次修改的入門範例,很適合拿來練習 jQuery 的動畫與事件操作。