案例:Tab欄切換
阿新 • • 發佈:2018-12-20
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> * { margin: 0; padding: 0; } ul { list-style-type: none; } .box { width: 400px; height: 300px; border: 1px solid #ccc; margin: 100px auto; overflow: hidden; } .hd { height: 45px; } .hd span { display: inline-block; width: 90px; background-color: pink; line-height: 45px; text-align: center; cursor: pointer; } .hd span.current { background-color: purple; } .bd li { height: 255px; background-color: purple; display: none; } .bd li.current { display: block; } </style> </head> <body> <div class="box" id="box"> <div class="hd"> <span class="current">體育</span> <span>娛樂</span> <span>新聞</span> <span>綜合</span> </div> <div class="bd"> <ul> <li class="current">我是體育模組</li> <li>我是娛樂模組</li> <li>我是新聞模組</li> <li>我是綜合模組</li> </ul> </div> </div> <script src="common.js"></script> <script> var box=document.getElementById("box"); var hd=box.getElementsByTagName("div")[0]; var bd=box.getElementsByTagName("div")[1]; var list=hd.getElementsByTagName("span"); var li=bd.getElementsByTagName("li"); for(var i=0;i<list.length;i++){ list[i].setAttribute("index",i); li[i].setAttribute("index","i"); list[i].onclick=function () { for(var j=0;j<list.length;j++){ list[j].removeAttribute("class");} this.className="current"; var num=this.getAttribute("index"); for(var k=0;k<li.length;k++){ li[k].removeAttribute("class"); } li[num].className="current"; }; } // //獲取最外面的div // var box=my$("box"); // //獲取的是裡面的第一個div // var hd=box.getElementsByTagName("div")[0]; // //獲取的是裡面的第二個div // var bd=box.getElementsByTagName("div")[1]; // //獲取所有的li標籤 // var list=bd.getElementsByTagName("li");//================================= // //獲取所有的span標籤 // var spans=hd.getElementsByTagName("span"); // //迴圈遍歷的方式,新增點選事件 // for(var i=0;i<spans.length;i++){ // //在點選之前就把索引儲存在span標籤中 // spans[i].setAttribute("index",i);//================================ // spans[i].onclick=function () { // //第一件事,所有的span的類樣式全部移除 // for(var j=0;j<spans.length;j++){ // spans[j].removeAttribute("class"); // } // // //第二件事,當前被點選的span應用類樣式 // this.className="current"; // //span被點選的時候獲取儲存的索引值 // //alert(this.getAttribute("index")); // var num=this.getAttribute("index");//============================== // // //獲取所有的li標籤,每個li標籤先全部隱藏 // for(var k=0;k<list.length;k++){ // list[k].removeAttribute("class"); // } // //當前被點選的span對應的li標籤顯示 // list[num].className="current"; // }; // } </script> </body> </html>