<html> <style type="text/css"> .current { background-color: red; } .dv { background-color: green; 200px; height: 200px; } </style> <head> <script type="text/javascript" src="change.js"></script> <script type="text/javascript">
/*********查询节点是否包含某个样式*******/ var hasClass = function(tag, clsName) { var arr = tag.className.split(/s+/); for (var i = 0; i < arr.length; i++) { if (arr[i] == clsName) { return true; } }; return false; } /*********扩展getElementsByClassName函数(兼容IE低版本)*********/ if (!document.getElementsByClassName) { document.getElementsByClassName = function(cls) { var nodeArr = []; var nodes = document.getElementsByTagName('*'); if (nodes && nodes.length > 0) { for (var i = 0; i < nodes.length; i++) { if (hasClass(nodes[i], cls)) { nodeArr.push(nodes[i]); } }; } return nodeArr; } } var changeTab = function(option) { // body... this.Init.apply(this, arguments); } changeTab.prototype = { /********参数的初始化********/ Init: function() { var arr = Array.prototype.slice.call(arguments); this.option = arr[0] || { inittab: 0, //设置选中的tab索引 tab: '', //tab的className tabclass: '', //tab点击之后的样式 container: '' //div的className }; }, /*************函数执行**************/ render: function() { ///获取要操作的tab和div this.tabs = document.getElementsByClassName(this.option.tab); this.contents = document.getElementsByClassName(this.option.container); if (this.tabs.length == 0 || this.contents.length == 0) { return; } if (this.tabs.length != this.contents.length) { return; } var that = this; ///由于闭包要用到此函数的参数,作用域不一致,所以要用that指向当前的函数 ////设置初始显示的tab和div内容 this.contents[this.option.inittab].style.display = 'block'; this.tabs[this.option.inittab].className = that.option.tab + ' ' + that.option.tabclass; for (var i = 0; i < this.tabs.length; i++) { /////闭包 (function(num) { that.tabs[num].onclick = function() { for (var k = 0; k < that.contents.length; k++) { ///隐藏所有div和去除所有tab样式 that.contents[k].style.display = 'none'; that.tabs[k].className = that.option.tab; }; ///显示和设置当前点击的tab和div内容 this.className = that.option.tab + ' ' + that.option.tabclass; that.contents[num].style.display = 'block'; } })(i); } }, /*************为函数扩展功能**************/ extend: function(obj) { if (obj && Object.prototype.toString.call(obj) == "[object Object]") { for (prop in obj) { this[prop] = obj[prop]; } } } } window.onload=function () { // body... var tb=new changeTab( { inittab: 0, tab:'sp', tabclass:'current', container:'dv' }); tb.render(); } </script> </head> <body> <div> <span class="sp" >111</span> <span class="sp">222</span> <span class="sp">333</span> </div> <div id=""> <div class="dv" style="display: none; ">dv1</div> <div class="dv" style="display: none; ">dv2</div> <div class="dv" style="display: none; ">dv3</div> <div> </body> </html>