<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> * { margin: 0; padding: 0; } ul { list-style: none; } #div { width: 640px; height: 480px; border: 2px solid #cccccc; margin: 100px auto; } #top { height: 45px; } #top span { display: inline-block; width: 154px; background-color: lightskyblue; line-height: 45px; text-align: center; cursor: pointer; } #top span.choose { background-color: deepskyblue; } #content li { display: none; } #content li.choose { display: block; } body { background-image: url("img/bg.gif"); } </style> </head> <body> <div id="div"> <div id="top"> <span class="choose">晉助</span> <span>半藏</span> <span>桂</span> <span>銀時</span> </div> <div id="content"> <ul> <li class="choose"><img src="img/yh1.jpg" alt=""/></li> <li><img src="img/yh2.jpg" alt=""/></li> <li><img src="img/yh3.jpg" alt=""/></li> <li><img src="img/yh4.jpg" alt=""/></li> </ul> </div> </div> <script> //獲取列表中的元素 var spanO=document.getElementsByTagName("span"); var liO=document.getElementsByTagName("li"); //迴圈遍歷每個span標籤 for(var i=0;i<spanO.length;i++) { //新增自定義屬性,索引 spanO[i].setAttribute("index",i); //註冊點選事件,新增事件處理函式 spanO[i].onclick=function() { //迴圈遍歷每個span for(var j=0;j<spanO.length;j++) { //移除span的樣式 spanO[j].removeAttribute("class"); } //給每個span賦予新樣式 this.className="choose"; //迴圈遍歷每個li for(var k=0;k<liO.length;k++) { //移除li的樣式 liO[k].removeAttribute("class"); } liO[this.getAttribute("index")].className="choose"; } } </script> </body> </html>
程式碼中圖片替換成自己的圖片,主要用到的是“排他思想”