<html> <head> <title>wirelib</title> </head> <script> //document.title = document.documentElement.clientWidth; /* * 1.onload 实例化对象 * 2.改造函数对象的属性及方法 * 3.使用了定时器,事件赋值函数,需注意闭包的使用 */ function TabSwitch(id) { var _this = this; var oDiv = document.getElementById(id); this.btns = oDiv.getElementsByTagName("input"); this.divs = oDiv.getElementsByTagName("div"); console.log(this) for (var i=0; i<this.btns.length; i++) { this.btns[i].index = i; //事件使用对象的方法,需转用闭包功能 this.btns[i].onclick = function(){ _this.tab(this);}; } } TabSwitch.prototype.tab = function(that){ alert(that); //触发事件对象 for (var i=0; i<this.btns.length; i++) { this.btns[i].className = ""; this.divs[i].style.display="none"; } that.className = "active"; this.divs[that.index].style.display="block"; } window.onload = function(){ var tab = new TabSwitch("oDiv"); } </script> <style> .active{border: 1px solid red;} </style> <body style="margin:10px; border: 10px solid red"> <div id="oDiv" style="border: 1px solid red; position: absolute; width:120px;height: 120px;"></canvas> <input type="button" value="a"/> <input type="button" value="b"/> <input type="button" value="c"/> <div>aaaa</div> <div style="display: none">bbbb</div> <div style="display: none">cccc</div> </body> </html>