焦點圖輪播需要同時滿足兩件事:沒人操作時自動輪播,使用者一介入就交還控制權。這份實作以 Koala UI 的 K.tabs 元件搭配 Qfast 模組載入器完成,設定項相當直覺,幾個參數就能控制自動播放、切換效果、頁碼按鈕與停留時間。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>JS 代碼實現圖片自動播放並可控的效果</title>
<link rel="stylesheet" type="text/css" href="https://hovertree.com/texiao/js/1/css/style.css">
<script type="text/javascript" src="https://hovertree.com/texiao/js/1/js/koala.min.1.5.js"></script>
<script type="text/javascript">
// 以模組方式按需載入動畫引擎,requires 宣告依賴於 fx 模組
Qfast.add('widgets', {
path: "https://hovertree.com/texiao/js/1/js/terminator2.2.min.js",
type: "js",
requires: ['fx']
});
Qfast(false, 'widgets', function () {
K.tabs({
id: 'decoroll2', // 焦點圖包裹層 id
conId: "decoimg_a2", // 大圖區域包裹 id
tabId: "deconum2", // 數字提示列 id
tabTn: "a", // 提示項的標籤名
conCn: '.decoimg_b2', // 單張圖的配置 class
auto: 1, // 是否自動播放:1 開啟,0 關閉
effect: 'fade', // 切換效果
eType: 'mouseover', // 觸發提示項切換的滑鼠事件
pageBt: true, // 是否顯示前後翻頁按鈕
bns: ['.prev', '.next'],// 前後按鈕的 class
interval: 3000 // 停留時間(毫秒)
});
});
</script>
</head>
<body>
<div>
<a href="https://hovertree.com">首頁</a>
<a href="https://hovertree.com/hvtart/bjae/f03e85410878db53.htm">原文</a>
<a href="https://hovertree.com/texiao/">特效庫</a>
</div>
<div id="decoroll2" class="imgfocus">
<div id="decoimg_a2" class="imgbox">
<div class="decoimg_b2">
<a href="https://hovertree.com/hvtart/bjae/f03e85410878db53.htm">
<img src="https://hovertree.com/texiao/js/1/img/1.jpg" alt="楊冪" />
</a>
</div>
<div class="decoimg_b2">
<a href="https://keleyi.com/">
<img src="https://hovertree.com/texiao/js/1/img/2.jpg" alt="范冰冰" />
</a>
</div>
<div class="decoimg_b2">
<a href="https://hovertree.com/shortanswer/">
<img src="https://hovertree.com/texiao/js/1/img/3.jpg" alt="高圓圓" />
</a>
</div>
<div class="decoimg_b2">
<a href="https://hovertree.com/guestbook/">
<img src="https://hovertree.com/texiao/js/1/img/4.jpg" alt="劉詩詩" />
</a>
</div>
</div>
<ul id="deconum2" class="num_a2">
<li><a href="javascript:void(0)">楊冪</a></li>
<li><a href="javascript:void(0)">范冰冰</a></li>
<li><a href="javascript:void(0)">高圓圓</a></li>
<li><a href="javascript:void(0)">劉詩詩</a></li>
</ul>
</div>
</body>
</html>
1. auto:設 0 就完全交給使用者操作,適合放在新聞列表上方的重點圖。
2. effect:fade 是淡入淡出,改成 slide 之類的滑動效果通常更有方向感。
3. interval:3000 是常見值。內容文字較多時建議拉長到 5000,否則使用者還沒讀完就換頁了。
4. pageBt / bns:前後箭頭要記得在 HTML 裡準備對應 class 的元素,否則設定不會生效。
1. 資源位址可能已失效。範例中的 hovertree.com CDN 與 YUI 系列依賴年代久遠,正式導入前請先確認可訪問,或下載到自有伺服器部署,避免第三方掛掉導致整塊功能失效。
2. 為每張圖補上 alt。原碼的 img 完全沒有 alt 屬性,螢幕閱讀器無法朗讀;上述範例已補上對應的提示文字。
3. 自動輪播要能被暫停。除了滑鼠移入,也應尊重系統的「減少動態效果」偏好:@media (prefers-reduced-motion: reduce) 下關閉自動播放,是無障礙設計的基本要求。
4. href="javascript:void(0)" 並不理想。它會讓連結無法用鍵盤右鍵開新分頁,且部分 CSP 政策會直接封鎖 javascript: 協定。改用 <button> 或 <a role="button"> 搭配事件監聽更恰當。
5. 大圖建議加上尺寸與 loading 屬性。設定 width/height 可避免版面位移(CLS),非首屏圖加 loading="lazy" 能省流量。
6. 若專案已使用現代框架,考慮改用 CSS scroll-snap 搭配 IntersectionObserver 實作,可以完全不用 JS 就完成自動輪播,效能與相容性都更好。