js 选项卡

今天在这里分享一下js选项卡的实现方法:

思路:  1.通过js获取标题内容的元素节点

     2.给标题元素添加下标属性

     3.添加点击事件

     4.点击标题时清空标题的css内容display:none;

     5.从新给标题添加css内容display:block;

css代码 

<style>
.tab_box{width: 350px; height: 350px;}
.tab_title{width: 100%; height: 50px;}
.tab_title li{border:1px solid #000; width: 100px; height: 100%; list-style: none; float: left; font-size: 20px; line-height: 50px; text-align: center;}
.content{display: none; width: 100%; height: 300px; text-align: center; line-height: 300px; font-size: 50px;}
.color{background: blue; color: #fff !important;}
</style>

html代码

 

<div class="tab_box">
  <ol class="tab_title" id="stt">
    <li class="color">红</li>
    <li>黄</li>
    <li>紫</li>
  </ol>
  <div class="content" style="display: block;" name="wyj">内容红</div>
  <div class="content" name = "wyj">内容黄</div>
  <div class="content" name = "wyj">内容紫</div>
</div>

js代码

<script>
  var oT = document.getElementById('stt');//获取标题父元素节点
  var oTi = oT.getElementsByTagName('li');//通过标题父元素节点获取标题元素节点
  var oC = document.getElementsByName('wyj');//获取内容节点
  for(var i = 0; i<oTi.length; i++){
    oTi[i].index = i;//给标题设置个下标属性 非常重要必须设置
    oTi[i].onclick = function(){
    for(var i = 0; i<oTi.length; i++){
      oTi[i].className = '';//清空标题css
      oC[i].style.display = 'none';//把所有内容display:none;
      }
    this.className = 'color';//给点击的标题设置css
    oC[this.index].style.display = 'block';出现当前点击标题对应的内容   this.index重要
    }
  }
</script>

本来想写一个可运行的实例代码的但是没有js代码发表的权限比较难过

  

 

posted @ 2018-09-14 10:06  破浪的小鱼  阅读(485)  评论(0编辑  收藏  举报