菜单栏展开和收起效果(纯js)

2014年6月25日 15:36:29

需要关注的是: 

1.用cookie保存用户当前点击的菜单项,不打扰后端代码

2.通过数学计算得到要显示和隐藏的div

3.点击事件是动态绑定到a标签上的,因此当dom加载完后,再执行js,也就是写在onload里

HTML如下:

 1 <h3 class="titleH3" id="101">aaaa</h3>
 2 <div class="subNav" id="1">
 3     <a href="#">1</a>
 4     <a href="#">2</a>
 5     <a href="#">3</a>
 6 </div>
 7 <h3 class="titleH3" id="102">bbbb</h3>
 8 <div class="subNav" id="2">
 9     <a href="#">11</a>
10     <a href="#">22</a>
11     <a href="#">33</a>
12 </div>

js如下:

 1 function showhide()
 2 {
 3     //绑定a链接的点击事件
 4     //点击a链接的时候将id写进cookie
 5     var arrSubNav = document.getElementsByClassName(‘subNav‘);
 6     for (var i = 0; i < arrSubNav.length; i++) {
 7         var arrHref = arrSubNav[i].getElementsByTagName(‘a‘);
 8         for (var j = 0; j < arrHref.length; j++) {
 9             arrHref[j].onclick = function () {
10                 var nodeParent = this.parentNode; //获取a链接所在的那个div块儿的id,注意,此处用this
11                 var idParent = nodeParent.getAttribute(‘id‘);
12                 document.cookie="userCheck="+idParent+";domain=***.***.com;path=/***"; //用cookie记录下用户当前的选择
13             }
14         }
15     }
16 
17     //从cookie里取值,展开指定div
18     userCheck = getUserCheckInfo();
19     if (userCheck > 0) {
20         for (var i = 0; i < arrSubNav.length; i++ ) {
21             arrSubNav[i].style.display = ‘none‘;
22         }
23         document.getElementById(userCheck).style.display = ‘block‘;
24     } else {
25         document.getElementById(‘3‘).style.display = ‘block‘;
26     }
27 
28     //点击标题时展开其下的菜单
29     var arrTitle = document.getElementsByClassName(‘titleH3‘);
30     for (var i = 0; i < arrTitle.length; i++) {
31         arrTitle[i].onclick = function () {
32             var idTitle = this.getAttribute(‘id‘);
33             var idSubNav = idTitle % 100; //根据title的id获取子菜单div的id
34             
35             for (var i = 0; i < arrSubNav.length; i++ ) {
36                 arrSubNav[i].style.display = ‘none‘;
37             }
38             document.getElementById(idSubNav).style.display = ‘block‘;
39 
40         }
41     };
42 }
43 
44 function getUserCheckInfo()
45 {
46     var strCookie = document.cookie;
47     //将多cookie切割为多个名/值对 
48     var arrCookie=strCookie.split("; "); 
49     var userCheck = ‘0‘; 
50     //遍历cookie数组,处理每个cookie对 
51     for(var i=0;i<arrCookie.length;i++) { 
52         var arr=arrCookie[i].split("="); 
53         if("userCheck"==arr[0]){ 
54             userCheck=arr[1]; 
55             break; 
56         } 
57     } 
58     return userCheck;
59 }

 变量名没有起好,userCheck应该为userChoice或者userSelected更恰当,他是用来保存用户点击的菜单的id的

菜单栏展开和收起效果(纯js),布布扣,bubuko.com

菜单栏展开和收起效果(纯js)

上一篇:android安装apk


下一篇:纯客户端页面关键字搜索高亮jQuery插件