码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象的tab选项卡

时间:2015-01-29 14:14:29      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

面向对象 this的问题  用定时器 用了事件的之后

首先我们先布局一下 按照常规的js来做一下选项卡, 

<style type="text/css">
  ul, li{ list-style-type: none; margin: 0; padding: 0}
  #div1{ width: 300px; height: 30px; background: #ccc}
  #div1 li{width: 100px; float: left;; text-align: center; line-height: 30px; list-style-type: none; }
  .active{ background: #999}
  #div2{ width: 300px; height: 300px; background: #eee}
  #div2 div{ display: none;}
</style>  
<script> window.onload = function(){ var oDiv1 = document.getElementById(‘div1‘); var oDiv2 = document.getElementById(‘div2‘); var oLi = oDiv1.getElementsByTagName(‘li‘); var oDiv = oDiv2.getElementsByTagName(‘div‘); for (var i = 0; i < oLi.length; i++) { oLi[i].index = i; oLi[i].onclick = function (){ for (var i = 0; i < oLi.length; i++) { oLi[i].className = ""; oDiv[i].style.display = ‘none‘; }; this.className = ‘active‘; oDiv[this.index].style.display = ‘block‘; } }; } </script> <div id="div1"> <ul> <li class="active">111111</li> <li>222222</li> <li>333333</li> </ul> </div> <div id="div2"> <div style="display:block">11111</div> <div>22222</div> <div>33333</div> </div>

下面我们来改写成面向对象

window.onload = function(){
   new TabSwitch(‘div1‘,‘div2‘);
   new TabSwitch(‘div3‘,‘div4‘)
}


function TabSwitch(id1,id2){
    var oDiv1 = document.getElementById(id1);
    var oDiv2 = document.getElementById(id2);
    this.oLi = oDiv1.getElementsByTagName(‘li‘);
    this.oDiv = oDiv2.getElementsByTagName(‘div‘);
    for (var i = 0; i < this.oLi.length; i++) {
      var _this = this;
      this.oLi[i].index = i;
      this.oLi[i].onclick = function(){
         _this.tab(this);
      }
    };
}
TabSwitch.prototype.tab = function(oli){
  for (var i = 0; i < this.oLi.length; i++) {
    this.oLi[i].className = "";
    this.oDiv[i].style.display = "none"  
  }
  oli.className = "active";
  this.oDiv[oli.index].style.display = "block"  
}
window.onload = function(){
   new TabSwitch(‘div1‘,‘div2‘);
}

function TabSwitch(id1,id2){//定义构造函数 两个参数为两个大div的id。
    var oDiv1 = document.getElementById(id1);
    var oDiv2 = document.getElementById(id2);
    this.oLi = oDiv1.getElementsByTagName(‘li‘);//定义为对象的属性
    this.oDiv = oDiv2.getElementsByTagName(‘div‘);//定义对象属性
    for (var i = 0; i < this.oLi.length; i++) {
      var _this = this; //改变this指向 次this指向new的对象保存在变量_this里
      this.oLi[i].index = i;
      this.oLi[i].onclick = function(){
         _this.tab(this);
      }
    };
}
TabSwitch.prototype.tab = function(oli){
  for (var i = 0; i < this.oLi.length; i++) {
    this.oLi[i].className = "";
    this.oDiv[i].style.display = "none"  
  }
  oli.className = "active";
  this.oDiv[oli.index].style.display = "block"  
}

 

面向对象的tab选项卡

标签:

原文地址:http://www.cnblogs.com/xingweb/p/4259542.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!