如何用js写一个简易选项卡

来源:互联网 发布:矩阵音响的连接 编辑:程序博客网 时间:2024/06/06 03:10

前面的html代码部分就不贴出来了,重点在js部分;

1.首先获取到需要的DOM元素

var oLi = document.getElementById('section').getElementsByTagName('li');var oUL=document.getElementById('detail').getElementsByTagName('ul');
2.对获取到的oLI循环遍历,添加onmouseenter事件
for(var i = 0;i<oLi.length;i++){    oLi[i].index=i;    oLi[i].onmouseenter=function(){                   } }
这里为什么要写oLi[i].index=i呢??后面会用到的;

3.在遍历了oLI添加事件后我们要对当前的li和对应的ul操作

<pre name="code" class="javascript">for(var i = 0;i<oLi.length;i++){    oLi[i].index=i;    oLi[i].onmouseenter=function(){            this.className='current';  //为当前的li添加样式                              oUl[this.index].display='block';   //获取当前的li对应的index,将对应的Ul显示出来 }
 }

4.为需要的li和ul添加操作了,不需要的呢?我们做相反的操作
for(var i=0;i<oLi.length;i++){            oLi[i].index=i;            oLi[i].onmouseenter=function(){            for(var n=0;n<oLi.length;n++){oLi[n].className='';}  //循环遍历li,置空所有li的class,写在<span style="font-family: Arial, Helvetica, sans-serif;">this.className='current'的前面否则会覆盖,下面同理;</span>                          this.className='current';                        for(var m=0;m<oUl.length;m++){oUl[n].style.display='none';}   //循环遍历ul,隐藏所有ul            oUl[this.index].style.display='block';                  <span style="font-family: Arial, Helvetica, sans-serif;"> //获取当前的li对应的index,将对应的Ul显示出来</span>                       } }


0 0