<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0px;
padding: 0px;
}
.three {
width: 150px;
}
.list,
.ul2 {
list-style: none;
}
.li1 {
background-color: rgb(104, 115, 235);
color: white;
text-align: center;
}
.li1:hover{
cursor: pointer;
}
.li2 {
background-color: rgba(239, 87, 87, 0.813);
text-align: center;
}
.ul2{
display: none;
}
.showdetails {
display: block;
}
</style>
</head>
<body>
<div class="three">
<ul class="list">
<li class="li1">
<p>百货</p>
<ul class="ul2">
<li class="li2">衣服</li>
<li class="li2">碗筷</li>
<li class="li2">电灯</li>
</ul>
</li>
<li class="li1">
<p>家电</p>
<ul class="ul2">
<li class="li2">电视机</li>
<li class="li2">电脑</li>
<li class="li2">洗衣机</li>
</ul>
</li>
<li class="li1" >
<P>水果</P>
<ul class="ul2" >
<li class="li2">苹果</li>
<li class="li2">桃子</li>
<li class="li2">葡萄</li>
</ul>
</li>
<li class="li1">
<p>蔬菜</p>
<ul class="ul2">
<li class="li2">黄瓜</li>
<li class="li2">西红柿</li>
<li class="li2">白菜</li>
</ul>
</li>
</ul>
</div>
<script>
//获得事件触发元素的对象
var li1s = document.querySelectorAll(".li1");
//获得要显示或隐藏的内容
var ul2s = document.querySelectorAll(".ul2");
//为每个对象绑定事件
for (let index = 0; index < li1s.length; index++) {
show(index);
};
//实现切换或展开
//每调用一次就为标题绑定单击事件,并且传入索引做参数
function show(index) {
li1s[index].onclick = function () {
//判断点击时内容是否隐藏,隐藏则显示,不隐藏则隐藏
if (ul2s[index].style.display == "none") {
ul2s[index].style.display = "block";
//此内容显示时关闭其他显示的内容
for(var i=0;i<ul2s.length;i++){
if(i!=index&& ul2s[i]!=="display"){
ul2s[i].style.display="none";
}
}
} else {
ul2s[index].style.display = "none";
}
}
};
</script>
</body>
</html>
08-11
3907
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-08
1622
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)