<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>选项卡</title> <style type="text/css"> *{margin:0;padding:0;} button{ width: 40px; height: 30px; line-height: 30px; text-align:center; } button.active{ background-color: yellow } .content{ width: 200px; height: 200px; border:2px solid red; display: none; } </style> </head> <body> <div class="wrapper"> <button class="active">11</button> <button>2</button> <button>3</button> <div class="content" style="display:block">1111111111</div> <div class="content">222222222</div> <div class="content">3333</div> </div> <script type="text/javascript"> var btn = document.getElementsByTagName(‘button‘); var content = document.getElementsByClassName(‘content‘); for (var i = 0; i < btn.length; i++) { //形成一个闭包 (function(n){ btn[n].onclick=function(){ //清除同级元素的当前类 for (var j = 0; j<btn.length; j++) { btn[j].className = ""; content[j].style.display = "none"; } //点击添加当前类 this.className = "active"; content[n].style.display = "block"; } }(i)) } </script> </body> </html>
效果图: