js选项卡实现

实现原理
    网页中常见的选项卡一般分为两块:标签和内容。当我们点击某个(或其他事件)标签时,对应的内容区域就会被激活,同时其他区域处于未激活状态。我们一般会给标签和内容的激活状态添加一个特别的样式(通常添加一个css类.active)来和未激活状态进行区分。 
    实现流程
  1. 清除所有标签的active样式
  2. 隐藏所有内容
  3. 给触发事件的标签添加active样式
  4. 显示对应内容
实现代码
HTML
<!DOCTYPE html>
<html>
<head lang="zh-cn">
  <meta charset="UTF-8">
  <title>选项卡</title>
</head>
<body>
  <div class="wrap">
    <div class="tab" id="tab">
      <a href="javascript:;" class="active">选项一</a>
      <a href="javascript:;">选项二</a>
      <a href="javascript:;">选项三</a>
    </div>
    <div class="con" id="con">
      <div class="active">内容一</div>
      <div>内容二</div>
      <div>内容三</div>
    </div>
  </div>
</body>
</html>
  
CSS
 1 * {
 2       font: 12px/1.5 'Arial', 'Microsoft YaHei';
 3       margin: 0;
 4       padding: 0;
 5     }
 6     .wrap {
 7       border-radius: 5px;
 8       box-shadow: 0 0 5px rgba(0, 0, 0, .5);
 9       margin: 50px auto 0;
10       width: 500px;
11     }
12 
13     .tab {
14       background: #323436;
15       border-top-left-radius: 5px;
16       border-top-right-radius: 5px;
17       font-size: 0;
18       text-align: center;
19     }
20     .tab a {
21       color: #8c8c8c;
22       display: inline-block;
23       height: 50px;
24       line-height: 50px;
25       text-align: center;
26       text-decoration: none;
27       transition: all .3s linear;
28       width: 80px;
29     }
30     .tab a:hover {
31       background: #454648;
32       color: #fff;
33     }
34     .tab .active {
35       background: #fb5240;
36       color: #fff;
37     }
38     .tab .active:hover {
39       background: #fb5240;
40     }
41 
42     .con div {
43       display: none;
44       height: 100px;
45       line-height: 100px;
46       text-align: center;
47     }
48 
49     .con .active {
50       display: block;
51     }

 

JavaScript

window.onload = function(){
      // 获取元素
      var aTab = document.getElementById('tab').getElementsByTagName('a'),
        aCon = document.getElementById('con').getElementsByTagName('div'),
        len = aTab.length,
        i;

      // 给标签绑定事件
      for(i = 0; i < len; i++ ){
        aTab[i].index = i; // 注意:给标签添加index属性绑定i值。
        aTab[i].onclick = function(){
          for(i = 0; i < len; i++){
            aTab[i].className = ''; // 重置所有标签的激活样式
            aCon[i].className = ''; // 重置所有内容的激活样式
          }
          this.className = 'active'; // 设置当前标签为激活状态
          aCon[this.index].className = 'active'; // 设置当前标签对应内容为激活状态
        };
      };
    };

 

posted @ 2015-02-15 15:22  tyxloveyfq  阅读(542)  评论(0编辑  收藏  举报