圖片要無縫循環捲動,關鍵是每次動畫結束後把最後一張搬到最前面,再把位移歸零,視覺上就完全接得上。
. 程式碼如下:
function refresh() {
var s = $(".box1");
if (!s.is(":animated"))
$(".box1").animate({ marginLeft: "0px" }, "slow", function () {
$('.box1 img:first').before($('.box1 img:last'));
$(".box1").css("margin-left", "-206px");
});
}
<div class="frame"><div class="box1"><img src="img/001.png" alt="" /><img src="img/002.png" alt="" /><img src="img/003.png" alt="" /><img src="img/004.png" alt="" /></div></div>
<button type="button"><<<</button><button type="button" onclick="refresh()">>>></button>
.box1
{
width:1200px;
overflow:hidden;
margin-left:-206px;
}
.frame
{
width:620px;
overflow:hidden;
}
兩個細節值得注意:is(":animated") 用來防止動畫尚未結束就重複觸發,避免位移錯亂;img:first 與 img:last 的搭配則完成循環搬移。圖片寬度預設 206px,程式碼中沒有另外設定,換圖片尺寸時記得同步調整 margin-left 與 css 裡的 -206px。