這個範例做了一個 980px 寬的橫幅輪播:上方是圖片區,下方是一排按鈕,點按鈕可跳到指定圖,滑鼠移入會暫停自動播放,離開後恢復。
<script language="javascript">
function tab_q(now_id) {
if (now_id == null) {
// 未指定時,抓目前顯示中的那一張
var c_show_id = $("#cont").find("div:visible").attr("id");
var nums_id = c_show_id.substring(1, 3); // 取 "c1" 裡的 "1"
var nums_next = parseInt(nums_id) + 1;
if (nums_next <= 8) {
// 還沒到最後一張
} else {
nums_next = 1; // 回到第一張
}
} else {
nums_next = now_id.substring(1, 3); // 從 "b3" 取出 "3"
}
$("#cont div").hide(); // 先全部隱藏
$("#butt div").css({ border: '#FF0000 0px solid' }); // 清掉所有按鈕邊框
$("#c" + nums_next).fadeIn(); // 淡入目標圖
$("#butt").find("#b" + nums_next).css({ border: '#FF0000 1px solid' }); // 對應按鈕加邊框
}
$(function() {
// 每 2 秒自動切換
auto = setInterval("tab_q()", 2000);
// 滑過圖片區:暫停自動播放
$("#cont div").each(function(i, n) {
$(n).hover(
function() { clearInterval(auto); },
function() { auto = setInterval("tab_q()", 2000); }
);
});
// 滑過按鈕:暫停並跳到該張
$("#butt div").each(function(i, n) {
$(n).hover(
function() {
clearInterval(auto);
tab_q($(this).attr("id"));
},
function() { auto = setInterval("tab_q()", 2000); }
);
});
});
</script>
<div style="width:980px; height:275px;">
<div id="cont" style="width:980px; height:241px; overflow:hidden; text-align:center">
<div id="c1"><img src="images/1.jpg" width="980"></div>
<div id="c2" style="display:none"><img src="images/2.jpg" width="980" height="241"></div>
<div id="c3" style="display:none"><img src="images/3.jpg" width="980" height="241"></div>
<!-- c4 ~ c8 依此類推 -->
</div>
<div id="butt" style="width:980px; height:31px">
<div id="b1" style="background-image:url(images/btn_1.png)"></div>
<div id="b2" style="background-image:url(images/btn_2.png)"></div>
<!-- b3 ~ b8 依此類推 -->
</div>
</div>
程式大量依賴 "c" + 數字 與 "b" + 數字 的命名規則,靠 substring(1, 3) 的字串切法取索引。這在項目超過 9 個時就會出錯("c10" 取到的只有 "1")。改用 index() 或 data 屬性會穩健得多:
var current = $("#cont div:visible").index();
var next = (current + 1) % total;
setInterval("tab_q()", 2000) 會把字串 eval 成程式碼。請直接傳函式參照:
auto = setInterval(tab_q, 2000);
auto = setInterval(...) 少了 var,會變成全域變數,多個輪播同時存在時會互相干擾。
滑鼠在按鈕上移動會反覆觸發 mouseenter/leave 組合,導致 clearInterval 與 setInterval 被瘋狂呼叫。應改用 mouseenter / mouseleave:
$('#butt div').on('mouseenter', stop).on('mouseleave', start);
「全部 hide 再 fadeIn」的過程中會出現一瞬空白。若想要平順的淡入淡出,應該讓兩張圖短暫重疊:
var $current = $('#cont div:visible');
var $next = $('#cont div').eq(next);
$next.fadeIn(400);
$current.fadeOut(400);
這個需求用 Swiper 幾行就完成了,還免費附贈觸控滑動、無限循環、自動播放暫停、鍵盤操作與可及性支援:
<div class="swiper">
<div class="swiper-wrapper">
<div class="swiper-slide"><img src="images/1.jpg"></div>
<div class="swiper-slide"><img src="images/2.jpg"></div>
</div>
<div class="swiper-pagination"></div>
</div>
<script>
new Swiper('.swiper', {
loop: true,
autoplay: { delay: 2000, disableOnInteraction: false },
pagination: { el: '.swiper-pagination', clickable: true }
});
</script>
若堅持自己實作,請記得加上 aria-hidden 標記非目前顯示的圖片、為自動播放提供暫停按鈕(WCAG 2.2.2 要求超過 5 秒的自動移動內容必須可暫停),並在 prefers-reduced-motion 生效時關閉動畫。