學習javascript面向對象 實例講解面向對象選項卡
更新時間:2016年01月04日 10:14:42 作者:小火柴的藍色理想
這篇文章主要介紹了面向對象選項卡實現方法,幫助大家更好地學習javascript面向對象,感興趣的小伙伴們可以參考一下
本文實例講解了最簡單的面向對象選項卡實現方法,分享給大家供大家參考,具體內容如下
效果圖:
1、功能說明
點擊三個按鈕分別顯示對應的選項卡
2、html代碼說明
<div class="box" id="box"> <ul class="list"> <li class="in_active">第一張選項卡</li> <li class="in">第二張選項卡</li> <li class="in">第三張選項卡</li> </ul> <nav class="conList"> <a class="con_active" href="javascript:;">第一個控制按鈕</a> <a class="con" href="javascript:;">第二個控制按鈕</a> <a class="con" href="javascript:;">第三個控制按鈕</a> </nav> </div>
3、css重點代碼說明
/*in為選項卡普通狀態(tài),默認不顯示*/ .in,.in_active{ display: none; width: 600px; height: 100px; background: orange; font-size: 50px; line-height: 100px; text-align: center; } /*in_active為選項卡選中狀態(tài),選中后顯示*/ .in_active{ display: block; } /*con為按鈕普通狀態(tài),默認文字顏色為黑色*/ .con,.con_active{ color: black; background-color: orange; } /*con_active為按鈕選中狀態(tài),選中后文字顏色為白色*/ .con_active{ color: white; }
4、js代碼說明
function Tab(obj){ /*元素獲取*/ //獲取選項卡展示部分 this.oList = obj.getElementsByTagName('ul')[0]; this.aIn = this.oList.getElementsByTagName('li'); //獲取選項卡控制部分 this.oConList = obj.getElementsByTagName('nav')[0]; this.aCon = this.oConList.getElementsByTagName('a'); /*變量設置*/ //選項卡張數 this.count = this.aIn.length; //當前第幾張 this.cur = 0; var _this = this; for(var i = 0; i < this.count; i++){ //設置索引 this.aCon[i].index = i; //給按鈕添加事件 this.aCon[i].onclick = function(){ _this.cur = this.index; _this.switch(); } } } Tab.prototype.switch = function(){ //去掉所有 for(var i = 0; i < this.count; i++){ this.aIn[i].className = 'in'; this.aCon[i].className = 'con'; } //顯示當前 this.aIn[this.cur].className = 'in_active'; this.aCon[this.cur].className = 'con_active'; } //獲取選項卡元素 var oBox = document.getElementById('box'); //構造選項卡對象 var tab1 = new Tab(oBox);
希望本文所述對大家學習javascript面向對象有所幫助。
相關文章
JavaScript正則表達式替換字符串中圖片地址(img src)的方法
這篇文章主要介紹了JavaScript正則表達式替換字符串中圖片地址(img src)的方法,結合實例形式分析了JS正則替換的常用技巧與注意事項,需要的朋友可以參考下2017-01-01不錯的用resizeTo和moveTo兩個函數實現窗口的“打乒乓球”效果
不錯的用resizeTo和moveTo兩個函數實現窗口的“打乒乓球”效果...2007-08-08