js面向对象实现Tab切换
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> input { width: 200px; height: 20px; background: white; } input.active { background: yellow; } #div1 div { width: 200px; height: 200px; background-color: #cccccc; display: none; } </style> </head> <body> <div id="div1"> <input type="button" value="a"> <input type="button" value="b"> <input type="button" value="c"> <div class="dv">a</div> <div class="dv">b</div> <div class="dv">c</div> </div> </body> <script> window.onload = function () { new TabSwitch('div1') } function TabSwitch(id) { var _this = this; var oDiv1 = document.getElementById(id); this.bTn = document.getElementsByTagName('input'); this.aDiv = document.getElementsByClassName('dv'); document.getElementsByTagName('input')[0].className = 'active'; document.getElementsByClassName('dv')[0].style.display = 'block'; for (var i = 0; i < this.bTn.length; i++) { this.bTn[i].index = i; this.bTn[i].onclick = function () { _this.fnClick(this); } } }; TabSwitch.prototype.fnClick = function (oBtn) { for (var i = 0; i < this.bTn.length; i++) { this.bTn[i].className = ''; this.aDiv[i].style.display = 'none'; } oBtn.className = 'active'; this.aDiv[oBtn.index].style.display = 'block'; } </script> </html>
赞 (0)