這個版本比基本輪播多了三件事:底部圓點導航、左右箭頭、以及滑鼠移入自動暫停的定時播放。它幾乎涵蓋了實務上輪播元件會用到的全部技巧,值得逐段拆解。
所有圖片排成橫向的一長串,容器 overflow:hidden 只看得到一格。切換時改的是 ul 的 margin-left。
.Xing_focus { width:875px; height:800px; overflow:hidden; border:1px solid red; }
.Xing_focus ul { width:3500px; }
.bnt li { width:18px; height:18px; background:red; cursor:pointer; margin-right:10px; float:left; }
.bnt .sli { background:blue; } /* 目前所在頁 */
<div class="Xing_focus" id="box">
<ul class="imgs" id="actor">
<li class="list1"><img src="..." alt="第一張" /></li>
<li class="list2"><img src="..." alt="第二張" /></li>
<li class="list3"><img src="..." alt="第三張" /></li>
<li class="list4"><img src="..." alt="第四張" /></li>
</ul>
<ul class="bnt" id="bnt"></ul> <!-- 圓點由 JS 動態產生 -->
<div class="pre" id="pre">上一張</div>
<div class="next" id="next">下一張</div>
</div>
var liW = $("#actor li:first").width();
var liL = $("#actor li").length;
for (var i = 0; i < liL; i++) { $("#bnt").append("<li></li>"); }
$("#bnt li:first").addClass("sli");
圓點數量直接由圖片數量決定,日後增減圖片不必改 JS。這是資料驅動畫面的基本思路。
$("#bnt li").each(function (index) {
$(this).click(function () {
if ($("#actor").is(":animated") == false) {
$("#actor").animate({ "marginLeft": -index * liW }, 500, function () {
$("#bnt li").removeClass("sli");
$("#bnt li").eq(index).addClass("sli");
});
}
});
});
注意狀態更新寫在動畫的完成回呼裡,而不是呼叫 animate 之後立刻執行。這樣圓點才會在畫面停穩時同步換色,不會提早跳。
var settime = window.setInterval(autoScroll, 2000);
$("#box").hover(function () {
window.clearInterval(settime); // 移入:停
}, function () {
settime = window.setInterval(autoScroll, 2000); // 移出:繼續
});
滑鼠移入就暫停,是因為使用者可能正在看某張圖或想點圓點,繼續跑會干擾操作。
$("#next").click(function () {
var ulM = parseInt($("#actor").css("margin-left"));
if (ulM == -((liL - 1) * liW) && $("#actor").is(":animated") == false) {
// 已在最後一張,動回 0
$("#actor").animate({ "marginLeft": 0 }, 500, function () { ... });
} else if ($("#actor").is(":animated") == false) {
$("#actor").animate({ "marginLeft": ulM - liW }, 500, function () { ... });
}
});
原版把回卷位置寫死成 -2625(等於 3 × 875),這在圖片數量變動時必然出錯。改成 -((liL - 1) * liW) 才是正確的資料驅動寫法。
原版把 autoScroll 定在同一個區塊內卻沒有限定作用域,實際上是全域函式;變數 i 也未宣告,同樣會外洩成全域。 these 都是 ES5 時代常見的疏漏,用 'use strict' 就會立刻報錯。
另外,用 margin-left 動畫會觸發重排。改用 transform: translateX() 搭配 CSS transition,動畫由合成器處理,順暢度與電量表現都好得多:
$("#actor").css("transform", "translateX(" + (-index * liW) + "px)");
/* CSS */
#actor { transition: transform .5s ease; }
最後,記得把箭頭與圓點改成 <button> 並加上 aria-label,自動播放務必提供暫停控制,並在 prefers-reduced-motion 時停用自動切換。這些不是加分項,而是輪播元件能不能被所有人使用的基本門檻。