tab切換案例實現 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> * { margin: 0; padding: 0; } ul { list-style-type: no ...
tab切換案例實現
<!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: yellow; } .bd li { height: 255px; background-color: hotpink; 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> //獲取div var box = my$("box"); //獲取第一個div var hd = box.getElementsByTagName("div")[0]; //獲取第二個div var bd = box.getElementsByTagName("div")[1]; //獲取第一個div裡面的span var spans = hd.getElementsByTagName("span"); //獲取第二個div裡面的li var list = bd.getElementsByTagName("li"); //遍歷span //點擊的時候, //先所有span的樣式移除 //再當前被電擊的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被點擊的時候獲取存儲的索引值 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>
實現效果: