面向對象選項卡
阿新 • • 發佈:2018-01-26
css style chan .class 自動 display 選項 highlight interval
HTML
<div id="div1"> <input class="active" type="button" value="1" /> <input type="button" value="2" /> <input type="button" value="3" /> <div style="display: block;">11111</div> <div>22222</div> <div>33333</div> </div> <div id="div2"> <input class="active" type="button" value="1" /> <input type="button" value="2" /> <input type="button" value="3" /> <div style="display: block;">11111</div> <div>22222</div> <div>33333</div> </div>
CSS
#div1 div, #div2 div{ border: 1px solid #000; width: 200px; height: 200px; display: none; } .active{ background: red; }
JS
//var oParent=document.getElementById(‘div1‘); //var aInput=oParent.getElementsByTagName(‘input‘); //var aDiv=oParent.getElementsByTagName(‘div‘); //init(); //function init(){ // for (var i=0;i<aInput.length;i++) { // aInput[i].index=i; // aInput[i].onclick=change; // } //} //function change(){ // for (var i=0;i<aInput.length;i++) { // aInput[i].className=‘‘; // aDiv[i].style.display=‘none‘; // } // this.className=‘active‘; // aDiv[this.index].style.display=‘block‘; //} //過程改為面向對象 //函數就是方法 //onload中創建對象 //全局變量就是屬性 //類似於class類例如student指學生 function Tab(uid){ this.oParent=document.getElementById(uid); this.aInput=this.oParent.getElementsByTagName(‘input‘); this.aDiv=this.oParent.getElementsByTagName(‘div‘); this.iNow=0; } Tab.prototype.demo=function(){ var This=this; for (var i=0;i<this.aInput.length;i++) { this.aInput[i].index=i; this.aInput[i].onclick=function(){ This.change(this); }; } } Tab.prototype.change=function(that){ for (var i=0;i<this.aInput.length;i++) { this.aInput[i].className=‘‘; this.aDiv[i].style.display=‘none‘; } that.className=‘active‘; this.aDiv[that.index].style.display=‘block‘; } //自動切換 Tab.prototype.autoPlay=function(){ var This=this; setInterval(function(){ if (This.iNow==This.aInput.length-1) { This.iNow=0; } else{ This.iNow++; } for (var i=0;i<This.aInput.length;i++) { This.aInput[i].className=‘‘; This.aDiv[i].style.display=‘none‘; } This.aInput[This.iNow].className=‘active‘; This.aDiv[This.iNow].style.display=‘block‘; },2000) } //創建單例 如具體學生某某 var tab=new Tab(‘div1‘); var tab1=new Tab(‘div2‘); tab.demo(); tab1.demo(); tab1.autoPlay();
面向對象選項卡