JS基础——伸缩菜单

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JS——伸缩菜单</title>
<style>
ul , h2 { padding:0; margin:0; }
li { list-style:none; }
#list { width:240px; border:1px solid #ccc; border-top:none; margin:0 auto; }
#list h2 { font-size:14px; border-top:1px solid #ccc; height:30px; line-height:30px; text-indent:20px; background:url(images/arr1.gif) no-repeat 5px center #eee; color:#000; cursor:pointer;}
#list .active { background:url(images/arr2.gif) no-repeat 5px center #ddd; color:#000; }
#list ul { display:none; }
#list ul li { line-height:24px; border-top:1px solid #ccc; text-indent:24px; }
#list ul .hover { background:#6FF; }
</style>
<script>
window.onload = function(){
	
	var oUl = document.getElementById('list');
	var aH2 = oUl.getElementsByTagName('h2');
	var aUl = oUl.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 = '';
				this.className = '';	
			}	
		};	
	}
		
};
</script>
</head>
<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>
</html>

思路:

1.获取相关元素

2.循环遍历所有的H2,并为每个H2添加索引

3.为每个H2添加点击事件,通过H2当前的className判断是否为空来显示隐藏ul,或添加删除当前H2的className

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值