圖片輪播常用於首頁橫幅或產品展示。以下範例以左側圖片區與右側指示欄構成,透過 jQuery 控制垂直位移,達到輪播效果。

最外層使用 dota 容器,內部包含 content 與 indicator 兩個主要區域。content 放置圖片列表,indicator 放置文字或縮圖按鈕。
content 使用絕對定位,透過改變 top 值移動圖片;indicator 則用背景圖切換 current 狀態。
.dota {
width: 570px;
height: 230px;
margin: 100px auto;
position: relative;
overflow: hidden;
}
.dota #content {
position: absolute;
width: 380px;
height: 230px;
}
.dota #content img {
width: 380px;
height: 230px;
}
.dota #indicator {
width: 180px;
background-color: #100F13;
}
.dota #indicator li.current {
background-position: 0 0;
}
先複製第一張圖片到最後,讓最後一張之後能平滑回到開頭。再用 setInterval 建立自動播放,滑鼠移入時暫停,移出時恢復。
$(function () {
var nowImage = 0;
$('#content').append($('#content li').first().clone());
var timer = setInterval(autoAnimate, 1500);
$('.dota').mouseenter(function () {
clearInterval(timer);
}).mouseleave(function () {
timer = setInterval(autoAnimate, 1500);
});
$('#indicator li').mouseenter(function () {
$(this).addClass('current').siblings().removeClass('current');
nowImage = $(this).index();
$('#content').stop().animate({ top: -230 * nowImage }, 1000);
});
function autoAnimate() {
if (nowImage === 4) {
nowImage = 0;
$('#indicator li').eq(nowImage).addClass('current').siblings().removeClass('current');
$('#content').stop().animate({ top: -230 * 5 }, 1000, function () {
$('#content').css('top', 0);
});
} else {
nowImage = nowImage + 1;
$('#indicator li').eq(nowImage).addClass('current').siblings().removeClass('current');
$('#content').stop().animate({ top: -230 * nowImage }, 1000);
}
}
});
此寫法的關鍵是 stop 方法,可避免連續觸發時動畫堆疊,讓切換更順暢。