<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
ul{
list-style: none;
width: 200px;
margin: 0 auto;
}
ul h3{
line-height: 50px;
background-color: aquamarine;
text-align: center;
}
ul p{
line-height: 150px;
border: 1px solid black;
display: none;
}
</style>
</head>
<body>
<ul>
<li><h3>菜单一</h3><p> 内容一 </p></li>
<li><h3>菜单二</h3><p> 内容二 </p></li>
<li><h3>菜单三</h3><p> 内容三 </p></li>
</ul>
<script>
var aH3 = document.getElementsByTagName('h3'); // [h3,h3,h3]
var aP = document.getElementsByTagName('p'); // [p,p,p]
for(var i = 0; i < aH3.length; i++){
aH3[i].index = i;
aH3[i].flag = 0;
aH3[i].onclick = function(){
if(this.flag == 0){
//先把所有p隐藏
for(var j = 0; j < aP.length; j++){
aP[j].style.display = "none";
aH3[j].flag = 0;
}
//再找到点击的h3标签下面的p标签显示
aP[this.index].style.display = "block";
this.flag = 1;
}else{
aP[this.index].style.display = "none";
this.flag = 0;
}
}
}
</script>
</body>
</html>