

一、初始化。頁面載入後取得容器、放數字索引的 li 集合、放圖片的 ul,並宣告計時器變數與目前索引 index。
二、啟動自動播放。用 setInterval 每 2 秒讓 index 遞增並呼叫切換函式。這裡有兩個關鍵:index 不能無限遞增,到底要歸零;呼叫切換函式時必須把遞增後的 index 傳進去。
三、切換函式。遍歷所有數字 li 先清掉 class;依傳入的 index 給對應的 li 加上高亮 class;同樣依 index 改變圖片容器的位置;最後把 index 同步成傳入值。若用位移做法,容器 top 值 = -index * 單張圖片高度(前提是所有圖片必須等高)。
四、滑過暫停。滑入容器時清除計時器,滑出時重新啟動並切到下一張。
五、數字導航。遍歷數字 li,滑過時呼叫切換函式並傳入該 li 的索引。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin:0; padding:0; list-style:none;}
.wrap{height:170px; width:490px; margin:60px auto; overflow: hidden; position: relative; margin:100px auto;}
.wrap ul{position:absolute;}
.wrap ul li{height:170px;}
.wrap ol{position:absolute; right:5px; bottom:10px;}
.wrap ol li{height:20px; width: 20px; background:#ccc; border:solid 1px #666; margin-left:5px; color:#000; float:left; line-height:center; text-align:center; cursor:pointer;}
.wrap ol .on{background:#E97305; color:#fff;}
</style>
<script type="text/javascript">
window.onload=function(){
var wrap=document.getElementById('wrap'),
pic=document.getElementById('pic').getElementsByTagName("li"),
list=document.getElementById('list').getElementsByTagName('li'),
index=0, timer=null;
// 定義並調用自動播放函數
timer = setInterval(autoPlay, 2000);
// 鼠標劃過整個容器時停止自動播放
wrap.onmouseover = function () { clearInterval(timer); }
// 鼠標離開整個容器時繼續播放至下一張
wrap.onmouseout = function () { timer = setInterval(autoPlay, 2000); }
// 遍歷所有數字導航實現劃過切換至對應的圖片
for (var i = 0; i < list.length; i++) {
list[i].onmouseover = function () {
clearInterval(timer);
index = this.innerText - 1;
changePic(index);
};
};
function autoPlay () {
if (++index >= pic.length) index = 0;
changePic(index);
}
// 定義圖片切換函數
function changePic (curIndex) {
for (var i = 0; i < pic.length; ++i) {
pic[i].style.display = "none";
list[i].className = "";
}
pic[curIndex].style.display = "block";
list[curIndex].className = "on";
}
};
</script>
</head>
<body>
<div class="wrap" id='wrap'>
<ul id="pic">
<li><img src="1.jpg" alt=""></li>
<li><img src="2.jpg" alt=""></li>
<li><img src="3.jpg" alt=""></li>
<li><img src="4.jpg" alt=""></li>
<li><img src="5.jpg" alt=""></li>
</ul>
<ol id="list">
<li class="on">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ol>
</div>
</body>
</html>
這個版本用 display 的顯示/隱藏來切換,勝在簡單直觀。若圖片很多,改成位移整條 ul 會更流暢,也能加上 CSS transition 做淡入淡出。記得換成自己的圖片檔名,並補上適當的 alt 文字。