思路:選項卡就是點擊按鈕切換到相應內容,其實就是點擊按鈕把內容通過display(block none)來實現切換的。
1、首先獲取元素。
2、for循環歷遍按鈕元素添加onclick 或者 onmousemove事件。
3、因為點擊當前按鈕時會以高亮狀態顯示,所以要再通過for循環歷遍把所有的按鈕樣式設置為空和把所有DIV的display設置為none。
4、把當前按鈕添加樣式,把當前DIV顯示出來,display設置為block。
注:給多個元素添加多個事件要用for循環歷遍。如選項卡是點擊切換,當前按鈕高度,點擊和按鈕高亮就是2個事件,所以要用2個for循環歷遍。
HTML代碼:
1 <div id="box"> 2 <input type="button" value="1" /> 3 <input type="button" value="2" /> 4 <input type="button" value="3" /> 5 <input type="button" value="4" /> 6 7 <div>1</div> 8 <div>2</div> 9 <div>3</div> 10 <div>4</div> 11 </div>
JS代碼:
1 <script> 2 window.onload=function(){ 3 var box=document.getElementById('box'); 4 var input=box.getElementsByTagName('input'); 5 var div=box..getElementsByTagName('div'); 6 7 for(var i=0;i<input.length;i++){ //循環歷遍onclick事件 8 input[i].index=i; //input[0].index=0 index是自定義屬性 9 input[i].onclick=function(){ 10 for(var i=0;i<input.length;i++){ //循環歷遍去掉button樣式和把div隱藏 11 input[i].className=''; 12 div[i].style.display='none'; 13 }; 14 this.className='active'; //當前按鈕添加樣式 15 div[this.index].style.display='block'; //div顯示 this.index是當前div 即div[0]之類的 16 }; 17 }; 18 }; 19 </script>