js实现选项卡功能

1、css

.liclick{
  border: 1px black solid;
  background: #fff;
  float: left;
  width: 80px;
  height: 35px;
  line-height: 35px;
  text-align: center;
}
.li{
  border: 1px black solid;
  background: #ccc;
  float: left;
  width: 80px;
  height: 35px;
  line-height: 35px;
  text-align: center;
}
.show{
  width: 244px;
  height: 240px;
  border: 1px black solid;
  position: relative;
  top:37px;
  left:40px;
}
.hide{
  display: none;
}

2、html

<html>
<head>
<title>导航栏作业</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="./css/tab_c.css">
<script src="./js/tabc.js"></script>
</head>
<body>
<ul>
  <li class="liclick" >选项1</li>
  <li class="li" >选项2</li>
  <li class="li" >选项3</li>
</ul>
<div class="show">
  111
</div>
<div class="hide">
  222
</div>
<div class="hide">
  33333
</div>
</body>
</html>
View Code

3、js代码

window.onload=function(){
  var a=document.getElementsByTagName('li');
  var b=document.getElementsByTagName('div');
  //alert(b[1].innerHTML);
  //这里用到了闭包
  for (var i = 0; i < a.length; i++) {
    (function(){
      var p=i;
      a[i].onclick=function(){
      for(var j=0; j<a.length; j++){
        if(p==j){
          a[j].setAttribute("class","liclick");
          b[j].setAttribute("class","show");
        }else {
          a[j].setAttribute("class","li");
          b[j].setAttribute("class","hide");
        }
      }
      /*if(p==0){
        a[0].setAttribute("class","liclick");
        a[1].setAttribute("class","li");
        a[2].setAttribute("class","li");
        b[0].setAttribute("class","show");
        b[1].setAttribute("class","hide");
        b[2].setAttribute("class","hide");
      }
      if(p==1){
        a[0].setAttribute("class","li");
        a[1].setAttribute("class","liclick");
        a[2].setAttribute("class","li");
        b[0].setAttribute("class","hide");
        b[1].setAttribute("class","show");
        b[2].setAttribute("class","hide");
      }
      if(p==2){
        a[0].setAttribute("class","li");
        a[1].setAttribute("class","li");
        a[2].setAttribute("class","liclick");
        b[0].setAttribute("class","hide");
        b[1].setAttribute("class","hide");
        b[2].setAttribute("class","show");
      }*/

      }
    })();
  }
}
View Code

 

posted on 2016-08-04 21:35  hgfs瑞  阅读(153)  评论(0编辑  收藏  举报

导航