原生js QQ列表展示小练习

来源:互联网 发布:ucsc数据库 编辑:程序博客网 时间:2024/06/05 08:39

html部分

<body><ul id="list">    <li class="lis">    <h2>我的好友</h2>    <ul>        <li>张三</li>        <li>张三</li>        <li>张三</li>        <li>张三</li>    </ul>  </li>    <li class="lis">    <h2>企业好友</h2>    <ul>        <li>李四</li>        <li>李四</li>        <li>李四</li>        <li>李四</li>        <li>李四</li>    </ul>  </li>    <li class="lis">    <h2>黑名单</h2>    <ul>        <li>张小三</li>        <li>李小四</li>    </ul>  </li></ul></body>

css部分

<style>    ul , h2 { padding:0; margin:0; }    li { list-style:none; }    #list { width:240px; border:1px solid #333; margin:0 auto; }    #list .lis {}    #list h2 { height:30px; line-height:30px; text-indent:20px;  background:url(img/ico1.gif) no-repeat 5px center #6FF; color:#000; }    #list .active { background:url(img/ico2.gif) no-repeat 5px center #FF9; color:#000; }    #list ul { display:none; }    #list ul li { line-height:24px; border-bottom:1px solid #333; text-indent:24px; }    #list ul .hover { background:#6FF; }</style>

js部分

var list = document.getElementById("list");var ah2 = list.getElementsByTagName("h2");var aul = list.getElementsByTagName("ul");for(var i=0; i<ah2.length; i++){    ah2[i].index = i; //索引值    ah2[i].onclick = function(){        if(this.className==""){            aul[this.index].style.display = "block";            this.className = "active";        }else{            aul[this.index].style.display = "none";            this.className = "";        }    }}

效果图

这里写图片描述