圖文輪播是門戶與電商頁面的標配組件。本文以一段 jQuery 代碼為例,拆解「自動播放 + 縮略圖切換 + 描述淡入淡出 + 可折疊說明區」這套組合效果的實現思路。
這個輪播包含幾個部分:
// 啟動自動輪播
intervalID = setInterval(cycleImage, slidetime);
// 展示描述層並設置透明度
$(".main_image .desc").show();
$(".main_image .block").animate({ opacity: 0.85 }, 1);
// 默認激活第一個縮略圖
$(".image_thumb ul li:first").addClass('active');
// 縮略圖點擊與懸停
$(".image_thumb ul li").click(function () {
// 取出當前縮略圖關聯的三項數據
var imgAlt = $(this).find('img').attr("alt");
var imgTitle = $(this).find('a').attr("href");
var imgDesc = $(this).find('.block').html();
var imgDescHeight = $(".main_image").find('.block').height();
if ($(this).is(".active")) {
// 已選中,不做處理
return false;
} else {
// 先把描述層淡出並下移,再換內容淡入
$(".main_image .block").animate({
opacity: 0,
marginBottom: -imgDescHeight
}, 250, function () {
$(".main_image .block").html(imgDesc).animate({
opacity: 0.85,
marginBottom: "0"
}, 250);
$(".main_image img").attr({ src: imgTitle, alt: imgAlt });
});
}
// 切換高亮項
$(".image_thumb ul li").removeClass('active');
$(this).addClass('active');
return false;
})
.hover(function () {
$(this).addClass('hover');
}, function () {
$(this).removeClass('hover');
});
// 折疊 / 展開描述區
$("a.collapse").click(function () {
$(".main_image .block").slideToggle();
$("a.collapse").toggleClass("show");
});
alt、href、內部 .block 分別承載說明文字、大圖地址與描述 HTML。切換時只改 DOM 屬性,不重新請求數據,響應很快。animate 的完成回調裡替換內容再淡入,避免文字硬切。marginBottom 配合負值:讓描述層向下滑出,視覺上比單純改透明度更有層次。active 表示當前項,點擊時先判斷是否已激活,避免重複播放動畫。如果要把這段代碼用到生產環境,建議補上幾點:
intervalID 全局可見,滑鼠懸停時最好 clearInterval,移開後再重啟,否則用戶正在閱讀時畫面突然跳動體驗很差。$.fn 擴展,防止污染全局命名空間。aria 屬性,讓屏幕閱讀器能讀出當前圖片說明。這段示例的價值在於把「定時、點擊、動畫、狀態標記」四件事串在了一起,理解之後換成任何輪播庫都能快速上手。