js实现无序列表

js

<script>
            window.onload = function(){
                //获得所有得段落元素
                var ps = document.getElementsByTagName("p")
                //获得所有无序列表
                var uls = document.getElementsByTagName("ul")
                for(var i =0,n=ps.length;i<n;i+=1){
                    //遍历段落
                    ps[i].id = i//添加到段落索引
                    ps[i].onclick = function(){//添加点击事件
                        if(uls[this.id].style.display!="block"){//如果无序列表为隐藏状态
                            for(var j = 0;j<n;j+=1){//遍历无序列表
                                uls[j].style.display = "none"
                            }
                            uls[this.id].style.display="block"//点击以后显示无序列表
                        }    
                        else{
                            //当前已显示的无序列表,再次点击后隐藏
                            uls[this.id].style.display="none"
                        }
                    }
                    
                    
                }
            }
        </script>

css

<style>
            *{
                margin: 0;
                padding: 0;
            }
            body{
                font-size: 14px;
            }
            a{
                text-decoration: none;
            }
            .menu{
                width: 210px;
                margin: 50px auto;
            }
            
            .menu p{
                color: #fff;
                height: 35px;
                cursor: pointer;
                line-height: 35px;
                background: #2980b9;
                border-bottom: 1px solid #ccc;
            }
            
            .menu ul{
                list-style:none;
                display: none;
                /*默认隐藏无序列表*/
            }
            
            .menu ul li{
                height: 33px;
                line-height: 33px;
                padding-left: 5px;
                background: #eee;
                border-bottom: 1px solid #ccc;
            }
            
        </style>

html

<div class="menu" id="menu">
			<div>
				<p>新闻管理</p>
			<ul>
				<li>用户管理</li>
				<li>用户管理</li>
			</ul>
			<p>新闻管理</p>
			<ul>
				<li>用户管理</li>
				<li>用户管理</li>
			</ul>
			<p>新闻管理</p>
			<ul>
				<li>用户管理</li>
				<li>用户管理</li>
			</ul>
			</div>
		</div>

  

 

posted @ 2022-05-09 20:04  ZosMa~  阅读(396)  评论(0)    收藏  举报