JS基于面向對象實現的選項卡效果示例
本文實例講述了JS基于面向對象實現的選項卡效果。分享給大家供大家參考,具體如下:
中間過渡環(huán)節(jié):把面向過程的程序,改寫成面向對象的形式
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <style> #div1 input {background:#CCC;} #div1 .active {background:yellow;} #div1 div {width:200px; height:200px; background:#CCC; display:none;} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>無標題文檔</title> <script> window.onload=function () { var oDiv=document.getElementById('div1'); var aBtn=oDiv.getElementsByTagName('input'); var aDiv=oDiv.getElementsByTagName('div'); var i=0; for(i=0;i<aBtn.length;i++) { aBtn[i].index=i; aBtn[i].onclick=function () { for(i=0;i<aBtn.length;i++) { aBtn[i].className=''; aDiv[i].style.display='none'; } this.className='active'; aDiv[this.index].style.display='block'; }; } }; </script> </head> <body> <div id="div1"> <input class="active" type="button" value="教育" /> <input type="button" value="財經" /> <input type="button" value="aaa" /> <div style="display:block;">1asdfasdfds</div> <div>2xzcvxzcv</div> <div>5332342345</div> </div> </body> </html>
改寫注意事項:
1.前提:所有代碼必須包含在window.onload里面
2.去掉函數嵌套(window.onload里面嵌套的函數拎到window.onload外面去)
3.不能有函數嵌套,但可以有全局變量(比如onclick函數拎出去后,aBtn是window.onload函數里的私有變量,onclick函數不能用)
過程:
1.onload(初始化整個程序)→構造函數(初始化一個對象)
2.全局變量→屬性
3.函數→方法
window.onload=function(){ var oTab=new TabSwitch("div1"); } function TabSwitch(id) { var oDiv=document.getElementById(id); this.aBtn=oDiv.getElementsByTagName('input'); this.aDiv=oDiv.getElementsByTagName('div'); var i=0; var _this=this; //this是new出來的對象,即oTab for(i=0;i<this.aBtn.length;i++) { this.aBtn[i].index=i; this.aBtn[i].onclick=function(){ _this.tab(this); //通過參數的形式,將被點擊的按鈕傳到下面去 }; } }; TabSwitch.prototype.tab=function(oBtn){ for(i=0;i<this.aBtn.length;i++) { this.aBtn[i].className=''; this.aDiv[i].style.display='none'; } oBtn.className='active'; //要被點擊的按鈕改變,而不是new出來的對象,所以這里不用this this.aDiv[oBtn.index].style.display='block'; }
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《javascript面向對象入門教程》、《JavaScript切換特效與技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript查找算法技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》、《JavaScript中json操作技巧總結》、《JavaScript錯誤與調試技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
相關文章
詳解webpack import()動態(tài)加載模塊踩坑
這篇文章主要介紹了詳解webpack import()動態(tài)加載模塊踩坑,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07高性能WEB開發(fā) flush讓頁面分塊,逐步呈現 flush讓頁面分塊,逐步呈現
在處理比較耗時的請求的時候,我們總希望先讓用戶先看到部分內容,讓用戶知道系統(tǒng)正在進行處理,而不是無響應。2010-06-06JavaScript?Echarts柱狀圖label優(yōu)化中問題針對講解
這篇文章主要介紹了JavaScript?Echarts柱狀圖label優(yōu)化中問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2022-12-12