<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{font-family: "Microsoft YaHei",serif;} body,dl,dd,p,h1,h2,h3,h4,h5,h6{margin: 0;} ol,ul,li{margin: 0;padding: 0;list-style: none;} img{border: none} #wrap{ margin: 50px auto; width: 820px; height: 390px; user-select: none; } #img{ position: relative; width: 100%; height: 340px; } #img ul{ width: 100%; height: 100%; } #img li{ display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } #img li.show{ display: block; } #tab{ overflow: hidden; width: 100%; height: 50px; } #tab ul{ width: 200%; height: 100%; } #tab li{ float: left; width: 10%; height: 50px; line-height: 50px; text-align: center; background-color: #000; font-size: 12px; color: #eeeeee; cursor: pointer; } #tab li.active{ background-color: #303030; color: #e9c06c; } </style> </head> <body> <div id="wrap"> <div id="img"> <ul> <li class="show"><a href=""><img src="../14作业案例/img/1.jpg" alt=""></a></li> <li><a href=""><img src="../14作业案例/img/2.jpg" alt=""></a></li> <li><a href=""><img src="../14作业案例/img/3.jpg" alt=""></a></li> <li><a href=""><img src="../14作业案例/img/4.jpg" alt=""></a></li> <li><a href=""><img src="../14作业案例/img/5.jpg" alt=""></a></li> </ul> </div> <div id="tab"> <ul> <li class="active">qwer</li> <li>qwer</li> <li>qwer</li> <li>qwer</li> <li>qwer</li> </ul> </div> </div> <script> var aTabLi = document.querySelectorAll('#tab ul li'), aImgLi = document.querySelectorAll('#img ul li'); var goudan = 0;//定义变量,用来表示当前显示的是哪张图片 // 给Tab对应的li添加点击事件 // 这里的var就是一个定值 // 就像在for外边let一样 for (var i=0,len = aTabLi.length;i<len;i++){ aTabLi[i].index = i; //自己给添加一个自定义index的属性 aTabLi[i].onclick = function () { var i = this.index; //用this使用aTabLi的index属性给i赋值 // 当使用var定义i的时候,没法再点击事件界面访问到i值,直接就是结果 if (goudan!==i){ // aTabLi[goudan].className = ""; aImgLi[goudan].className = ""; // 当前点击的tab样式添加 aTabLi[i].className = "active"; aImgLi[i].className = "show"; //当前显示的图片序号变更 goudan = i; } }; } </script> </body> </html>