<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>实现伸缩二级菜单</title>
<script src="jquery-3.2.1.min.js"></script>
<style>
li {
list-style: none;
}
li span {
padding-left: 20px;
cursor: pointer;
}
.open {
background:url("../images/minus.png") no-repeat center left;
}
.closed {
background: url("../images/add.png") no-repeat center left;
}
.show {
display: block;
}
.hide {
display: none;
}
</style>
</head>
<body>
<ul class="tree">
<li>
<span class="open">电子产品</span>
<ul class="show">
<li>手机</li>
<li>ipad</li>
<li>台式机</li>
</ul>
</li>
<li>
<span class="closed">家电用品</span>
<ul class="hide">
<li>洗衣机</li>
<li>空调</li>
<li>冰箱</li>
</ul>
</li>
<li>
<span class="closed">服装</span>
<ul class="hide">
<li>男士上衣</li>
<li>男士裤子</li>
<li>女士上衣</li>
<li>女士裤子</li>
<li>女士裙子</li>
</ul>
</li>
</ul>
<script>
// 1. 为span元素绑定click事件
$("span").click(function(){
// 2. 事件的处理函数 - 判断当前span元素的样式
// 定位触发click事件的span
if($(this).hasClass("open")){
// 3. 当前class为open,改为closed,ul的class改为hide
$(this).attr("class","closed");
$(this).next().attr("class","hide");
}else{
// 4. 当前class为closed,改为open,ul的class改为show
$(this).attr("class","open");
$(this).next().attr("class","show");
}
});
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>实现伸缩二级菜单</title>
<script src="jquery-3.2.1.min.js"></script>
<style>
li {
list-style: none;
}
li span {
padding-left: 20px;
cursor: pointer;
}
.open {
background:url("../images/minus.png") no-repeat center left;
}
.closed {
background: url("../images/add.png") no-repeat center left;
}
.show {
display: block;
}
.hide {
display: none;
}
</style>
</head>
<body>
<ul class="tree">
<li>
<span class="open">电子产品</span>
<ul class="show">
<li>手机</li>
<li>ipad</li>
<li>台式机</li>
</ul>
</li>
<li>
<span class="closed">家电用品</span>
<ul class="hide">
<li>洗衣机</li>
<li>空调</li>
<li>冰箱</li>
</ul>
</li>
<li>
<span class="closed">服装</span>
<ul class="hide">
<li>男士上衣</li>
<li>男士裤子</li>
<li>女士上衣</li>
<li>女士裤子</li>
<li>女士裙子</li>
</ul>
</li>
</ul>
<script>
// 1. 为span元素绑定click事件
$("span").click(function(){
// 2. 事件的处理函数 - 判断当前span元素的样式
// 定位触发click事件的span
if($(this).hasClass("open")){
// 3. 当前class为open,改为closed,ul的class改为hide
$(this).attr("class","closed");
$(this).next().attr("class","hide");
}else{
// 4. 当前class为closed,改为open,ul的class改为show
$(this).attr("class","open");
$(this).next().attr("class","show");
}
});
</script>
</body>
</html>