>  기사  >  웹 프론트엔드  >  객체지향 자바스크립트를 배우고, example_javascript 스킬로 객체지향 탭에 대해 설명해보세요.

객체지향 자바스크립트를 배우고, example_javascript 스킬로 객체지향 탭에 대해 설명해보세요.

WBOY
WBOY원래의
2016-05-16 15:22:041077검색

본 글의 예시에서는 가장 간단한 객체지향 탭 구현 방법을 설명하고 있으며, 참고용으로 모두와 공유합니다

렌더링:

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为选项卡普通状态,默认不显示*/
.in,.in_active{
 display: none;
 width: 600px;
 height: 100px;
 background: orange;
 font-size: 50px;
 line-height: 100px;
 text-align: center;
}
/*in_active为选项卡选中状态,选中后显示*/
.in_active{
 display: block;
}
/*con为按钮普通状态,默认文字颜色为黑色*/
.con,.con_active{
 color: black;
 background-color: orange;
}
/*con_active为按钮选中状态,选中后文字颜色为白色*/
.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 객체지향을 배우는 모든 사람에게 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.