不依賴任何函式庫的圖片輪播,其實只需要三件事:一個放圖的 img、一排可點的清單、一個負責換 src 的函式。這份範例刻意用最基礎的 DOM API 寫,適合拿來理解事件模型。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title></title>
<style>
*{ margin:0; padding:0; }
.all{ width:600px; height:350px; position:relative; overflow:hidden; margin:100px auto; }
.all ul{ z-index:1; position:relative; }
.all ul li{ position:absolute; top:0; left:0; }
.all ol{ position:absolute; right:10px; bottom:10px; z-index:2; }
.all ol li{ width:20px; height:20px; border:1px solid #fff; background-color:#333; float:left; overflow:hidden; margin-right:10px; text-align:center; line-height:20px; color:#fff; margin-top:10px; font-weight:bold; }
.all ol .current{ width:30px; height:30px; border:1px solid #f60; color:#f60; line-height:30px; margin-top:0; cursor:pointer; }
</style>
<script>
//通過id值獲得元素的函數
function $(id){ return document.getElementById(id); }
//初始化函數
function initial(){
olLi = document.getElementsByTagName('ol')[0].getElementsByTagName('li');//獲取ol下的li
ol = $('tab');//獲取ol元素
theImg = $('theImg');
//五張圖片的地址
addressPic = ['01.jpg','02.jpg','03.jpg','04.jpg','05.jpg'];
//遍歷ol下的li
for(var i=0;i<olLi.length;i++){
//依次給每個li綁定mouseover事件
olLi[i].addEventListener('mouseover', changePicture, false);
olLi[i].index = i;//設置ol li的index序列號
}
}
//切換圖片
function changePicture(e){
e.target.className = "current";//將選中的li的class設置為current
//清除ol裡的空白節點
cleanWhitespace(ol);
//刪除除當前選中的li外其他li的class屬性值
var nextNode = e.target.nextSibling;//當前節點的下一個節點
var lastNode = e.target.previousSibling;//當前節點的前一個節點
while(nextNode){//將當前節點後所有的兄弟節點的class屬性清除
nextNode.setAttribute('class','');
nextNode = nextNode.nextSibling;
}
while(lastNode){//將當前節點前面所有的兄弟節點的class屬性清除
lastNode.className = '';
lastNode = lastNode.previousSibling;
}
//實現切換圖片的功能
theImg.src = addressPic[this.index];
}
//清除ol下的空白節點
function cleanWhitespace(oElement) {
for(var i=0;i<oElement.childNodes.length;i++){
var node = oElement.childNodes[i];
if(node.nodeType==3 && !/\S/.test(node.nodeValue)){
node.parentNode.removeChild(node);
}
}
}
//給窗體綁定load事件
window.addEventListener('load', initial, false);
</script>
</head>
<body>
<div class="all">
<ul>
<li><img id="theImg" src="01.jpg" width="600px" height="350px"/></li>
</ul>
<ol id="tab">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li class="current">5</li>
</ol>
</div>
</body>
</html>
為什麼要清除空白節點?HTML 中標籤之間的換行與縮排會被解析成文字節點(nodeType == 3),如果直接用 nextSibling 遍歷兄弟,會一路撞到這些看不見的節點。範例在初始化時先掃掉純空白的文字節點,後續的 while(nextNode) 迴圈才能順利跑完。用 nextElementSibling 可以從根本上避開這個問題,是更現代的寫法。
this.index 從哪來?初始化時幫每個 li 掛了一個自訂屬性 index,事件觸發時 this 就是那個 li,因此 this.index 能取到正確序號。用 dataset(el.dataset.index)會更規範。
高亮切換的邏輯先把被點的 li 設為 current,再沿著 previousSibling 與 nextSibling 兩側清空其他項的 class,就完成「單選」效果。
目前用 mouseover 觸發,手機上沒有 hover,建議同時監聽 click 或改用 pointerenter;圖片切換是硬跳,加上一層 opacity 的 CSS transition 就能變成淡入淡出;若要自動播放,再用 setInterval 週期性呼叫同一個函式即可。