效果如图所示:
ES5:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #container { width: 670px; margin: 0; padding: 0; } .box { width: 670px; height: 400px; border: 1px solid black; clear: both; display: none; } ul { list-style: none; } ul li { float: left; width: 200px; height: 50px; line-height: 50px; margin-left: 5px; border: 1px solid #ddd; text-align: center; cursor: pointer; } .color { background-color: brown; color: #fff; } </style> </head> <body> <div id="container"> <ul> <li class="color">第一页</li> <li>第二页</li> <li>第三页</li> </ul> <div class="box" style="display: block;">第一模块</div> <div class="box">第二模块</div> <div class="box">第三模块</div> </div> <script> var lis = document.querySelectorAll('li'); var div = document.querySelector('#container').querySelectorAll('div') console.log(div); for (var i = 0; i < lis.length; i++) { lis[i].setAttribute('index', i) lis[i].onclick = function () { for (var i = 0; i < lis.length; i++) { lis[i].className = '' } this.className = 'color' var index = this.getAttribute('index'); for (var i = 0; i < div.length; i++) { div[i].style.display = 'none' } div[index].style.display = 'block' } } </script> </body> </html>
ES6写法:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>面向对象-选项卡</title> <style> #container { width: 670px; margin: 0; padding: 0; } .box { width: 670px; height: 400px; border: 1px solid black; clear: both; display: none; } ul { list-style: none; } ul li { float: left; width: 200px; height: 50px; line-height: 50px; margin-left: 5px; border: 1px solid #ddd; text-align: center; cursor: pointer; } .box{ display: none; } .color { background-color: brown; color: #fff; } </style> </head> <body> <div id="div2"> <ul> <li class="color">第一页</li> <li>第二页</li> <li>第三页</li> </ul> </div> <div class="box" style="display:block;">第一模块</div> <div class="box">第二模块</div> <div class="box">第三模块</div> </body> </html> <script type="text/javascript"> window.onload = function () { var oTab = new Tab("div2"); } var lis = null; var div = null; function Tab(id){ var div2 = document.getElementById(id); this.lis = div2.getElementsByTagName('li');//全局变量 转变成属性 this.div = document.getElementsByClassName('box'); var _this =this;//将这里的对象this存入_this中,方便在列表点击里面用 for(i=0;i<this.lis.length;i++){ this.lis[i].index = i; this.lis[i].onclick = function () { _this.tab(this);//这里的this指的是列表,把它作为参数传到函数中; } } } Tab.prototype.tab = function (lis){//函数 转变成对象的方法 // alert(this); //这里的this指的是对象object; for(i=0;i<this.lis.length;i++){ this.lis[i].className = ''; this.div[i].style.display = 'none'; } lis.className = 'color'; this.div[lis.index].style.display = 'block'; } </script>